<?php
/**
 * member actions.
 *
 * @package    sf_sandbox
 * @subpackage member
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class memberActions extends sfActions
{
    public function executeForgetPassword()
    {
        if ($this->getRequestParameter('email') && $this->getRequestParameter('username')) {
            $email = $this->getRequestParameter('email');
            $username = $this->getRequestParameter('username');

            $this->email = $email;
            $this->username = $username;

            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $username);
            $c->add(MlmDistributorPeer::EMAIL, $email);
            $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $existDistributor = MlmDistributorPeer::doSelectOne($c);

            if ($existDistributor) {
                $c = new Criteria();
                $c->add(AppUserPeer::USERNAME, $username);
                $c->add(AppUserPeer::USER_ROLE, Globals::ROLE_DISTRIBUTOR);
                $c->add(AppUserPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
                $existUser = AppUserPeer::doSelectOne($c);

                if ($existUser) {
                    /****************************/
                    /*****  Send email **********/
                    /****************************/
                    error_reporting(E_STRICT);

                    date_default_timezone_set(date_default_timezone_get());

                    include_once('class.phpmailer.php');

                    $password = $existUser->getUserpassword();

                    $subject = $this->getContext()->getI18N()->__("Tune International Group User Password requested", null, 'email');
                    $body = $this->getContext()->getI18N()->__("Dear %1%", array('%1%' => $existDistributor->getNickname()), 'email') . ",<p><p>
                    <p>" . $this->getContext()->getI18N()->__("Your login password for tune-venture.com. ", null, 'email') . "</p>
                    <p><b>" . $this->getContext()->getI18N()->__("Shareholder ID", null) . ": " . $username . "</b>
                    <p><b>" . $this->getContext()->getI18N()->__("Password", null) . ": " . $password . "</b>";

                    $mail = new PHPMailer();
                    $mail->IsMail(); // telling the class to use SMTP
                    $mail->Host = Globals::EMAIL_HOST; // SMTP server
                    $mail->Sender = Globals::EMAIL_FROM_NOREPLY;
                    $mail->From = Globals::EMAIL_FROM_NOREPLY;
                    $mail->FromName = Globals::EMAIL_FROM_NOREPLY_NAME;
                    $mail->Subject = $subject;
                    $mail->CharSet="utf-8";

                    $text_body = $body;

                    $mail->Body = $body;
                    $mail->AltBody = $text_body;
                    $mail->AddAddress($existDistributor->getEmail(), $existDistributor->getNickname());

                    if (!$mail->Send()) {
                        echo $mail->ErrorInfo;
                    }
                    $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Password already sent to your email account. Please check your inbox."));
                } else {
                    $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Email is not matching to your username."));
                }
            } else {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Email is not matching to your username."));
            }
        }
    }
    public function executeFlushBonusByTree()
    {
        if (sfConfig::get('sf_environment') == Globals::SF_ENVIRONMENT_DEV) {
            $flushDistArrs = explode("|", "|29479295|");

            for ($y = count($flushDistArrs); $y > 0; $y--) {
                if ($flushDistArrs[$y] == "") {
                    continue;
                }
                $flushDistId = $flushDistArrs[$y];
                print_r("flushDistId=".$flushDistId);
                print_r("<br>");
                $c = new Criteria();
                $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $flushDistId, Criteria::EQUAL);
                $distributor = MlmDistributorPeer::doSelectOne($c);

                $arrs = explode("|", $distributor->getTreeStructure());
                $uplinePosition = $distributor->getPlacementPosition();
                $sponsoredPackageDB = MlmPackagePeer::retrieveByPK($distributor->getRankId());
                $pairingPoint = $sponsoredPackageDB->getPrice();

                for ($x = count($arrs); $x > 0; $x--) {
                    if ($arrs[$x] == "" || $arrs[$x] == $flushDistId) {
                        continue;
                    }
                    $uplineDistDB = $this->getDistributorInformation($arrs[$x]);
                    print_r($uplineDistDB->getDistributorCode()."=".$uplinePosition);

                    $this->updateDistPairingLeader($uplineDistDB->getDistributorId(), $uplinePosition, $pairingPoint, "FLUSH BY ADMINISTRATOR", Globals::PAIRING_LEDGER_FLUSH);
                    $uplinePosition = $uplineDistDB->getPlacementPosition();
                    print_r("<br>");
                }
            }
            print_r("Done");
        }
        return sfView::HEADER_ONLY;
    }
    public function executeFlushDummy()
    {
        //if (sfConfig::get('sf_environment') == Globals::SF_ENVIRONMENT_DEV) {
            $c = new Criteria();
            $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%CNTV0001%", Criteria::LIKE);
            //$c->addAnd(MlmDistributorPeer::DISTRIBUTOR_CODE, "49464771", Criteria::NOT_EQUAL);

            $distributors = MlmDistributorPeer::doSelect($c);
            foreach ($distributors as $distributor) {
                print_r($distributor->getDistributorCode());
                $leftBalance = $this->findPairingLedgers($distributor->getDistributorId(), Globals::PLACEMENT_LEFT, null);
                $rightBalance = $this->findPairingLedgers($distributor->getDistributorId(), Globals::PLACEMENT_RIGHT, null);

                print_r("=".$leftBalance."|".$rightBalance);
                if ($leftBalance != 0) {
                    $this->flushDistPairingLeader($distributor->getDistributorId(), Globals::PLACEMENT_LEFT, $leftBalance, "FLUSH BY ADMINISTRATOR");
                }
                if ($rightBalance != 0) {
                    $this->flushDistPairingLeader($distributor->getDistributorId(), Globals::PLACEMENT_RIGHT, $rightBalance, "FLUSH BY ADMINISTRATOR");
                }
                print_r("<br>");
            }
            print_r("Done");
        //}
        return sfView::HEADER_ONLY;
    }
    public function executeInitData_BAK()
    {
        if (sfConfig::get('sf_environment') == Globals::SF_ENVIRONMENT_DEV) {
            date_default_timezone_set(date_default_timezone_get());

            /*$array = array("8888", "MlmAdmin");

            foreach ($array as $i => $value) {
                $app_user = new AppUser();
                $app_user->setUsername($value);
                $app_user->setKeepPassword("admin123");
                $app_user->setUserpassword("admin123");
                $app_user->setKeepPassword2("admin123");
                $app_user->setUserpassword2("admin123");
                $app_user->setUserRole(Globals::ROLE_SUPERADMIN);
                $app_user->setStatusCode(Globals::STATUS_ACTIVE);
                $app_user->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $app_user->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $app_user->save();

                $mlm_admin = new MlmAdmin();
                $mlm_admin->setAdminCode($app_user->getUsername());
                $mlm_admin->setUserId($app_user->getUserId());
                $mlm_admin->setStatusCode(Globals::STATUS_ACTIVE);
                $mlm_admin->setAdminRole(Globals::ROLE_ADMIN);
                $mlm_admin->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_admin->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_admin->save();
            }

            $array1 = array("TV1", "TV2", "TV3", "TV4", "TV5", "TV6", "TV7");
            $array2 = array("TV01", "TV001", "TV0001", "T01", "T001", "T0001", "V01", "V001");
            $array3 = array("CNTV01", "CNTV02", "CNTV03", "CNTV04", "CNTV05", "CNTV06");
            $array4 = array("CNTV001", "CNTV002", "CNTV003", "CNTV004", "CNTV005", "CNTV006");
            $array5 = array("CNTV0001");

            $result = array_merge($array1, $array2);
            $result = array_merge($result, $array3);
            $result = array_merge($result, $array4);
            $result = array_merge($result, $array5);

            foreach ($result as $i => $value) {
                $app_user = new AppUser();
                $app_user->setUsername($value);
                $app_user->setKeepPassword("123456");
                $app_user->setUserpassword("123456");
                $app_user->setKeepPassword2("123456");
                $app_user->setUserpassword2("123456");
                $app_user->setUserRole(Globals::ROLE_DISTRIBUTOR);
                $app_user->setStatusCode(Globals::STATUS_ACTIVE);
                $app_user->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $app_user->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $app_user->save();

                $mlm_distributor = new MlmDistributor();
                $mlm_distributor->setDistributorCode($value);
                $mlm_distributor->setUserId($app_user->getUserId());
                $mlm_distributor->setStatusCode(Globals::STATUS_PENDING);
                $mlm_distributor->setFullName($value);
                $mlm_distributor->setNickname($value);
                $mlm_distributor->setIc($value);
                $mlm_distributor->setCountry("Malaysia");
                $mlm_distributor->setAddress($i);
                $mlm_distributor->setPostcode($i);
                $mlm_distributor->setEmail($i . "@yahoo.com");
                $mlm_distributor->setContact($i);
                $mlm_distributor->setGender("M");
                $mlm_distributor->setDob(date("Y/m/d h:i:s A"));
                $mlm_distributor->setBankName($i);
                $mlm_distributor->setBankAccNo($i);
                $mlm_distributor->setBankHolderName($i);
                $mlm_distributor->setParentId(1);
                $mlm_distributor->setTotalLeft(1);
                $mlm_distributor->setTotalRight(1);
                $mlm_distributor->setTreeLevel(1);
                $mlm_distributor->setTreeStructure(1);
                $mlm_distributor->setUplineDistId(1);
                $mlm_distributor->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_distributor->save();
            }*/

            /* ****************************************
             *      Package
             ******************************************/
            /*$arr[0] = array(
                'package' => "Bronze"
            , 'price' => 1000
            , 'direct_sponsor' => 6
            , 'pairing_bonus' => 6
            , 'world_pool' => 0
            , 'daily_max' => 1000
            );
            $arr[1] = array(
                'package' => "Silver"
            , 'price' => 3000
            , 'direct_sponsor' => 8
            , 'pairing_bonus' => 8
            , 'world_pool' => 0
            , 'daily_max' => 3000
            );
            $arr[2] = array(
                'package' => "Gold"
            , 'price' => 5000
            , 'direct_sponsor' => 10
            , 'pairing_bonus' => 10
            , 'world_pool' => 1
            , 'daily_max' => 5000
            );
            $arr[3] = array(
                'package' => "Platinum"
            , 'price' => 15000
            , 'direct_sponsor' => 12
            , 'pairing_bonus' => 12
            , 'world_pool' => 3
            , 'daily_max' => 15000
            );
            $arr[4] = array(
                'package' => "Diamond"
            , 'price' => 30000
            , 'direct_sponsor' => 14
            , 'pairing_bonus' => 14
            , 'world_pool' => 6
            , 'daily_max' => 30000
            );
            $arr[5] = array(
                'package' => "VIP"
            , 'price' => 50000
            , 'direct_sponsor' => 16
            , 'pairing_bonus' => 16
            , 'world_pool' => 8
            , 'daily_max' => 30000
            );
            $arr[6] = array(
                'package' => "VVIP"
            , 'price' => 100000
            , 'direct_sponsor' => 18
            , 'pairing_bonus' => 18
            , 'world_pool' => 12
            , 'daily_max' => 30000
            );

            foreach ($arr as $i => $value) {
                $mlm_package = new MlmPackage();
                $mlm_package->setPackageName($value['package']);
                $mlm_package->setPrice($value['price']);
                $mlm_package->setDirectSponsor($value['direct_sponsor']);
                $mlm_package->setPairingBonus($value['pairing_bonus']);
                $mlm_package->setWorldPool($value['world_pool']);
                $mlm_package->setDailyMaxPairing($value['daily_max']);
                $mlm_package->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_package->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));


                $mlm_package->save();
            }*/

            /* ********************************
             *      Account
             * *********************************/
            /*$arr[0] = array(
                'name' => "CNTV01,CNTV02,CNTV03,CNTV001,CNTV002,CNTV003,CNTV0001"
            , 'price' => "Platinum"
            , 'price' => 15000
            );
            $arr[1] = array(
                'name' => "CNTV04,CNTV05,CNTV06,CNTV004,CNTV005,CNTV006"
            , 'price' => "Gold"
            , 'price' => 5000
            );

            $this->doActivateAccount(1, 1, 7);*/
            /* ********************************
             *      Test
             * *********************************/
            /*$dateUtil = new DateUtil();
            $date = mktime(0, 0, 0, 26, 3, 2012); // current date
            for ($x = 1; $x < 60; $x++) {
                $date = $dateUtil->addDate($date, 1, 0, 0);

                $mlm_eshare_log = new MlmEshareLog();
                $mlm_eshare_log->setShareValue(0.1);
                $mlm_eshare_log->setCreatedBy(0);
                $mlm_eshare_log->setCreatedOn($date);
                $mlm_eshare_log->setUpdatedBy(0);
                $mlm_eshare_log->save();
            }*/

            /*$level = 0;
            $sponsorDB = MlmDistributorPeer::retrieveByPk(30);

            while ($level < 100) {
                var_dump($sponsorDB->getUplineDistId());
                var_dump($sponsorDB->getUplineDistCode());
                print_r("<br>");
                if ($sponsorDB->getUplineDistId() == 0 || $sponsorDB->getUplineDistCode() == null) {
                    break;
                }
                $sponsorDB = MlmDistributorPeer::retrieveByPk($sponsorDB->getUplineDistId());
                $level++;
            }*/

            /*$uplineDistDB = $this->getDistributorInformation("TV7");
            $uplinePosition = "LEFT";
            $arrs = explode("|", $uplineDistDB->getTreeStructure());
            print_r($arrs);
            for ($x = count($arrs); $x > 0; $x--) {
                if ($arrs[$x] == "") {
                    continue;
                }
                var_dump($arrs[$x]);
                $uplineDistDB = $this->getDistributorInformation($arrs[$x]);
                $this->forward404Unless($uplineDistDB);
                $totalLeft = $uplineDistDB->getTotalLeft();
                $totalRight = $uplineDistDB->getTotalRight();
                if (Globals::PLACEMENT_LEFT == $uplinePosition) {
                    $uplineDistDB->setTotalLeft($totalLeft + 1);
                } else if (Globals::PLACEMENT_RIGHT == $uplinePosition) {
                    $uplineDistDB->setTotalRight($totalRight + 1);
                }
                //$uplineDistDB->save();
                $uplinePosition = $uplineDistDB->getPlacementPosition();
            }*/

            // Output
            /*$dateUtil = new DateUtil();

            $d = $dateUtil->getMonth();
            $firstOfMonth = date('Y-m-j', $d["first_of_month"])." 00:00:00";
            $lastOfMonth = date('Y-m-j', $d["last_of_month"])." 23:59:59";

            $c = new Criteria();
            $c->addAnd(MlmEshareLogPeer::CREATED_ON, $firstOfMonth, Criteria::GREATER_EQUAL);
            $c->addAnd(MlmEshareLogPeer::CREATED_ON, $lastOfMonth, Criteria::LESS_EQUAL);
            $mlmEshareLogs = MlmEshareLogPeer::doSelect($c);
            var_dump(count($mlmEshareLogs));*/

            /*$dateUtil = new DateUtil();
            var_dump($dateUtil->formatDate("Y-m-d", date("Y-m-d")));

            $c = new Criteria();
            $c->add(MlmDailyBonusLogPeer::BONUS_TYPE, Globals::DAILY_BONUS_LOG_TYPE_DAILY);
            $c->addDescendingOrderByColumn(MlmDailyBonusLogPeer::BONUS_DATE);
            $mlmDistPairingDBs = MlmDailyBonusLogPeer::doSelectOne($c);

            var_dump($dateUtil->formatDate("Ymd", $mlmDistPairingDBs->getBonusDate()));

            print_r("==<br>");
            print_r("==<br>");

            var_dump(date('j'));

            $date = split("-", date('Y-m-d'));
            var_dump($date);
            $bonus_date = date('Y-m-d', mktime(0, 0, 0, $date[1], $date[2], $date[0]));
            $cf_date = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - 18, date("Y")));
            $today = date('Y-m-d');
            $bdate = date('d');
            $bmonth = date('m');
            $byear = date('Y');

            var_dump($bonus_date);
            print_r("a<br>");
            var_dump($cf_date);
            print_r("b<br>");
            var_dump($today);
            print_r("<br>");
            var_dump($bdate);
            print_r("<br>");
            var_dump($bmonth);
            print_r("<br>");
            var_dump($byear);
            print_r("<br>");

            //$bdate = str_pad($number, 2, "0", STR_PAD_LEFT);
            $bdate = $date[2];
            //$bmonth = '1';
            $bmonth = $date[1];
            //$byear = '2012';
            $byear = $date[0];

            $cf_date = date('Y-m-d', mktime(0, 0, 0, $bmonth, $bdate - 1, $byear));
            $bonus_date = date('Y-m-d', mktime(0, 0, 0, $bmonth, $bdate, $byear));
            $today = date('Y-m-d', mktime(0, 0, 0, $bmonth, $bdate + 1, $byear));*/

            /*$volume = 50000;
            for ($i = 0.1; $i <= 0.5; $i = $i + 0.01) {
                print_r($i."<br>");
                $mlm_eshare_price_setting = new MlmEsharePriceSetting();
                $mlm_eshare_price_setting->setShareValue($i);
                $mlm_eshare_price_setting->setVolume($volume);
                $mlm_eshare_price_setting->setStatusCode("ACTIVE");
                $mlm_eshare_price_setting->setCreatedBy(0);
                $mlm_eshare_price_setting->setUpdatedBy(0);
                $mlm_eshare_price_setting->save();

                $volume = $volume + 50000;
            }*/

            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, 524);
            //$c->setLimit(100);
            $distributors = MlmDistributorPeer::doSelect($c);
            foreach ($distributors as $distributor) {
                print_r("DIST ID". $distributor->getDistributorId());
                print_r("<br>");

                /*$c = new Criteria();
                $c->add(MlmDistPairingLedgerPeer::DIST_ID, $distributor->getDistributorId());
                //$c->add(MlmDistPairingLedgerPeer::LEFT_RIGHT, Globals::PLACEMENT_LEFT);
                $c->addAscendingOrderByColumn(MlmDistPairingLedgerPeer::PAIRING_ID);
                $pairingLedgers = MlmDistPairingLedgerPeer::doSelect($c);

                $leftBalance = 0;
                $rightBalance = 0;
                print_r("<br>");
                foreach ($pairingLedgers as $pairingLedger) {
                    if ($pairingLedger->getLeftRight() == Globals::PLACEMENT_LEFT) {
                        $leftBalance = $leftBalance + $pairingLedger->getCredit() - $pairingLedger->getDebit();
                        $pairingLedger->setBalance($leftBalance);
                    }
                    if ($pairingLedger->getLeftRight() == Globals::PLACEMENT_RIGHT) {
                        $rightBalance = $rightBalance + $pairingLedger->getCredit() - $pairingLedger->getDebit();
                        $pairingLedger->setBalance($rightBalance);
                    }
                    $pairingLedger->save();
                    print_r("leftBalance=".$leftBalance);
                    print_r("rightBalance=".$rightBalance);
                    print_r("<br>");
                }
                $this->revalidatePairing($distributor->getDistributorId(), Globals::PLACEMENT_LEFT);
                $this->revalidatePairing($distributor->getDistributorId(), Globals::PLACEMENT_RIGHT);*/
                $c = new Criteria();
                $c->add(MlmAccountLedgerPeer::DIST_ID, $distributor->getDistributorId());
                $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ESHARE);
                $c->addAscendingOrderByColumn(MlmAccountLedgerPeer::ACCOUNT_ID);
                $accountLedgers = MlmAccountLedgerPeer::doSelect($c);

                $balance = 0;
                print_r("<br>");
                foreach ($accountLedgers as $accountLedger) {

                    $balance = $balance + $accountLedger->getCredit() - $accountLedger->getDebit();
                    $accountLedger->setBalance($balance);
                    $accountLedger->save();
                    print_r("balance=".$balance);
                    print_r("<br>");
                }
                $c = new Criteria();
                $c->add(MlmAccountLedgerPeer::DIST_ID, $distributor->getDistributorId());
                $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
                $c->addAscendingOrderByColumn(MlmAccountLedgerPeer::ACCOUNT_ID);
                $accountLedgers = MlmAccountLedgerPeer::doSelect($c);

                $balance = 0;
                print_r("<br>");
                foreach ($accountLedgers as $accountLedger) {

                    $balance = $balance + $accountLedger->getCredit() - $accountLedger->getDebit();
                    $accountLedger->setBalance($balance);
                    $accountLedger->save();
                    print_r("ecash balance=".$balance);
                    print_r("<br>");
                }
                $this->revalidateAccount($distributor->getDistributorId(), Globals::ACCOUNT_TYPE_ESHARE);
                $this->revalidateAccount($distributor->getDistributorId(), Globals::ACCOUNT_TYPE_ECASH);
            }
            print_r("Done");
        }
        return sfView::HEADER_ONLY;
    }

    public function executeInitData()
    {
        $volume = 50000;
        for ($i = 0.1; $i <= 0.5; $i = $i + 0.005) {
            print_r($i."<br>");
            $mlm_eshare_price_setting = new MlmEsharePriceSetting();
            $mlm_eshare_price_setting->setShareValue($i);
            $mlm_eshare_price_setting->setVolume($volume);
            $mlm_eshare_price_setting->setStatusCode("ACTIVE");
            $mlm_eshare_price_setting->setCreatedBy(0);
            $mlm_eshare_price_setting->setUpdatedBy(0);
            $mlm_eshare_price_setting->save();

            if ($i >= 0.1 && $i <= 0.15) {
                $volume = $volume + 50000;
            } else if ($i > 0.15 && $i <= 0.25) {
                $volume = $volume + 100000;
            } else if ($i > 0.25 && $i <= 0.35) {
                $volume = $volume + 150000;
            } else if ($i > 0.35) {
                $volume = $volume + 200000;
            }
        }
        /*$c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, 36);
        //$c->setLimit(100);
        $distributors = MlmDistributorPeer::doSelect($c);
        foreach ($distributors as $distributor) {
            print_r("DIST ID". $distributor->getDistributorId());
            print_r("<br>");

            $c = new Criteria();
            $c->add(MlmAccountLedgerPeer::DIST_ID, $distributor->getDistributorId());
            $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ESHARE);
            $c->addAscendingOrderByColumn(MlmAccountLedgerPeer::ACCOUNT_ID);
            $accountLedgers = MlmAccountLedgerPeer::doSelect($c);

            $balance = 0;
            print_r("<br>");
            foreach ($accountLedgers as $accountLedger) {

                $balance = $balance + $accountLedger->getCredit() - $accountLedger->getDebit();
                $accountLedger->setBalance($balance);
                $accountLedger->save();
                print_r("ecash balance=".$balance);
                print_r("<br>");
            }

            $this->revalidateAccount($distributor->getDistributorId(), Globals::ACCOUNT_TYPE_ESHARE);
        }*/

        //if (sfConfig::get('sf_environment') == Globals::SF_ENVIRONMENT_DEV) {
            /*$c = new Criteria();
            $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_SHARE_MARKET);
            $settingDB = AppSettingPeer::doSelectOne($c);
            $settingDB->setSettingValue(0);
            $settingDB->save();

            $shareArrs = explode(",", "TV1,CNTV02,CNTV03,CNTV04,CNTV07,66369606,13517855,73033391,59179212,68174029,72586390,38554030,98221745,21404351,34670148,32026587,98795277,77613404,61183882,35539712,93127682");

            for ($y = 0; $y < count($shareArrs); $y++) {
                print_r($shareArrs[$y]);
                print_r("<br>");
                $c = new Criteria();
                $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $shareArrs[$y], Criteria::LIKE);
                $distributor = MlmDistributorPeer::doSelectOne($c);
                $amount = 0;
                if ($shareArrs[$y] == "TV1") {
                    $amount = 100000;
                } else {
                    $sponsoredPackageDB = MlmPackagePeer::retrieveByPK($distributor->getRankId());
                    $amount = $sponsoredPackageDB->getPrice() * $sponsoredPackageDB->getShareRatio() / 100;
                }

                $this->buyShare($amount, $distributor->getDistributorId());
            }*/
        //}
        print_r("Done");
        return sfView::HEADER_ONLY;
    }

    function buyShare($buyAmount, $distId) {

        $eshareTradingService = new EShareTradingService();
        $eshareTradingDto = $eshareTradingService->fetchAllShareTradingData($distId);
        $ecash = $eshareTradingDto->getEcash();


        $dateUtil = new DateUtil();
        $eshareValue = $eshareTradingDto->getEsharePrice();
        $totalEshare = $buyAmount / $eshareValue;

        $unitArrs = explode(",", Globals::ESHARE_SPLIT_SELL_UNIT);
        $dayArrs = explode(",", Globals::ESHARE_SPLIT_SELL_DAY);

        $totalEshareConclude = 0;
        for ($i = 0; $i < count($unitArrs); $i++) {
            $totalEsharePartition = ceil($unitArrs[$i] / 100 * $totalEshare);
            $totalEshareConclude += $totalEsharePartition;

            $currentDate = $dateUtil->formatDate("Y-m-d", date("Y-m-d"))." 00:00:00";
            $validSellDate = $dateUtil->addDate($currentDate, $dayArrs[$i], 0, 0);

            $mlm_dist_eshare_account = new MlmDistEshareAccount();
            $mlm_dist_eshare_account->setDistId($distId);
            $mlm_dist_eshare_account->setBuyPrice($eshareValue);
            $mlm_dist_eshare_account->setCredit($totalEsharePartition);
            $mlm_dist_eshare_account->setSellPrice(0);
            $mlm_dist_eshare_account->setDebit(0);
            $mlm_dist_eshare_account->setProfit(0);
            $mlm_dist_eshare_account->setShareBalance($totalEsharePartition);
            $mlm_dist_eshare_account->setRemark("");
            $mlm_dist_eshare_account->setValidSellDate($validSellDate);
            //$mlm_dist_eshare_account->setSellDate("$y-$m-$d");
            $mlm_dist_eshare_account->setStatusCode(Globals::ESHARE_ACCOUNT_STATUS_ACTIVE);
            $mlm_dist_eshare_account->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_dist_eshare_account->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_dist_eshare_account->save();
        }

        /* ******************************
         *  Update Account Ecash
         ******************************* */
        $c = new Criteria();
        $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
        $c->addAnd(MlmAccountPeer::DIST_ID, $distId);
        $mlmAccount = MlmAccountPeer::doSelectOne($c);
        $accountEcashBalance = $mlmAccount->getBalance();

        $mlm_account_ledger = new MlmAccountLedger();
        $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
        $mlm_account_ledger->setDistId($distId);
        $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_BUY_ESHARE);
        $mlm_account_ledger->setRemark("");
        $mlm_account_ledger->setCredit(0);
        $mlm_account_ledger->setDebit($buyAmount);
        $mlm_account_ledger->setBalance($accountEcashBalance - $buyAmount);
        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->save();

        $this->revalidateAccount($distId, Globals::ACCOUNT_TYPE_ECASH);

        /* ******************************
         *  Update Account EShare
         ******************************* */
        $c = new Criteria();
        $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ESHARE);
        $c->addAnd(MlmAccountPeer::DIST_ID, $distId);
        $mlmAccount = MlmAccountPeer::doSelectOne($c);
        $accountEshareBalance = $mlmAccount->getBalance();

        $mlm_account_ledger = new MlmAccountLedger();
        $mlm_account_ledger->setDistId($distId);
        $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ESHARE);
        $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_BUY);
        $mlm_account_ledger->setRemark("");
        $mlm_account_ledger->setCredit($totalEshareConclude);
        $mlm_account_ledger->setDebit(0);
        $mlm_account_ledger->setBalance($accountEshareBalance + $totalEshareConclude);
        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->save();

        $this->revalidateAccount($distId, Globals::ACCOUNT_TYPE_ESHARE);

    }

    public function executeIndex()
    {
        return $this->redirect('/member/summary');
    }

    public function executeDownloadAttachment()
    {
        $response = $this->getResponse();
        $response->clearHttpHeaders();
        $response->addCacheControlHttpHeader('Cache-control','must-revalidate, post-check=0, pre-check=0');
        $response->setContentType('application/pdf');
        $response->setHttpHeader('Content-Transfer-Encoding', 'binary', TRUE);
        $response->setHttpHeader('Content-Disposition','attachment; filename=Tune_Hotels_Proposed_Listing.pdf', TRUE);
        $response->sendHttpHeaders();
        readfile("Tune_Hotels_Proposed_Listing.pdf");
        return sfView::NONE;
    }

    public function executeDownloadSellEshareAttachment()
    {
        $response = $this->getResponse();
        $response->clearHttpHeaders();
        $response->addCacheControlHttpHeader('Cache-control','must-revalidate, post-check=0, pre-check=0');
        $response->setContentType('application/pdf');
        $response->setHttpHeader('Content-Transfer-Encoding', 'binary', TRUE);
        $response->setHttpHeader('Content-Disposition','attachment; filename=sell_eshare_procedure.pdf', TRUE);
        $response->sendHttpHeaders();
        readfile("sell_eshare_procedure.pdf");
        return sfView::NONE;
    }

    public function executeDownloadEshareAttachment()
    {
        $response = $this->getResponse();
        $response->clearHttpHeaders();
        $response->addCacheControlHttpHeader('Cache-control','must-revalidate, post-check=0, pre-check=0');
        $response->setContentType('application/pdf');
        $response->setHttpHeader('Content-Transfer-Encoding', 'binary', TRUE);
        $response->setHttpHeader('Content-Disposition','attachment; filename=buy_share_flow.pdf', TRUE);
        $response->sendHttpHeaders();
        readfile("buy_share_flow.pdf");
        return sfView::NONE;
    }

    public function executeRegister()
    {
        $char = strtoupper(substr(str_shuffle('abcdefghjkmnpqrstuvwxyz'), 0, 2));
        // Concatenate the random string onto the random numbers
        // The font 'Anorexia' doesn't have a character for '8', so the numbers will only go up to 7
        // '0' is left out to avoid confusion with 'O'

        $str = rand(1, 7) . rand(1, 7) . $char;
        $this->getUser()->setAttribute(Globals::SYSTEM_CAPTCHA_ID, $str);
    }

    public function executeRegisterInfo()
    {
        if (!$this->getUser()->hasAttribute(Globals::SESSION_USERNAME)) {
            return $this->redirect('/member/register');
        }
    }

    public function executeUpdateProfile()
    {
        $mlm_distributor = MlmDistributorPeer::retrieveByPK($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($mlm_distributor);

        $mlm_distributor->setNickname($this->getRequestParameter('nickName'));
        $mlm_distributor->setFullName($this->getRequestParameter('fullname'));
        $mlm_distributor->setIc($this->getRequestParameter('ic'));
        if ($this->getRequestParameter('country') == 'China') {
            $mlm_distributor->setCountry('China (PRC)');
        } else {
            $mlm_distributor->setCountry($this->getRequestParameter('country'));
        }
        $mlm_distributor->setAddress($this->getRequestParameter('address'));
        $mlm_distributor->setPostcode($this->getRequestParameter('postcode'));
        $mlm_distributor->setEmail($this->getRequestParameter('email'));
        $mlm_distributor->setContact($this->getRequestParameter('contactNumber'));
        $mlm_distributor->setGender($this->getRequestParameter('gender'));
        if ($this->getRequestParameter('dob')) {
            list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
            $mlm_distributor->setDob("$y-$m-$d");
        }
        $mlm_distributor->setBankName($this->getRequestParameter('bankName'));
        $mlm_distributor->setBankAccNo($this->getRequestParameter('bankNo'));
        $mlm_distributor->setBankHolderName($this->getRequestParameter('bankHolder'));
        $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_distributor->save();

        $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Profile update successfully"));

        return $this->redirect('/member/viewProfile');
    }

    public function executeDoRegister()
    {
        $fcode = $this->generateFcode($this->getRequestParameter('country'));
        $password = $this->getRequestParameter('userpassword');

        $parentId = $this->getParentId($this->getRequestParameter('sponsorId'));
        $this->forward404Unless($parentId <> 0);

        $app_user = new AppUser();
        $app_user->setUsername($fcode);
        $app_user->setKeepPassword($password);
        $app_user->setUserpassword($password);
        $app_user->setKeepPassword2($password);
        $app_user->setUserpassword2($password);
        $app_user->setUserRole(Globals::ROLE_DISTRIBUTOR);
        $app_user->setStatusCode(Globals::STATUS_PENDING);
        $app_user->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $app_user->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $app_user->save();

        // ****************************
        $mlm_distributor = new MlmDistributor();
        $mlm_distributor->setDistributorCode($fcode);
        $mlm_distributor->setUserId($app_user->getUserId());
        $mlm_distributor->setStatusCode(Globals::STATUS_PENDING);
        $mlm_distributor->setFullName($this->getRequestParameter('fullname'));
        $mlm_distributor->setNickname($this->getRequestParameter('nickName'));
        $mlm_distributor->setIc($this->getRequestParameter('ic'));
        if ($this->getRequestParameter('country') == 'China') {
            $mlm_distributor->setCountry('China (PRC)');
        } else {
            $mlm_distributor->setCountry($this->getRequestParameter('country'));
        }
        $mlm_distributor->setAddress($this->getRequestParameter('address'));
        $mlm_distributor->setPostcode($this->getRequestParameter('postcode'));
        $mlm_distributor->setEmail($this->getRequestParameter('email'));
        $mlm_distributor->setContact($this->getRequestParameter('contactNumber'));
        $mlm_distributor->setGender($this->getRequestParameter('gender'));
        if ($this->getRequestParameter('dob')) {
            list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
            $mlm_distributor->setDob("$y-$m-$d");
        }
        $mlm_distributor->setBankName($this->getRequestParameter('bankName'));
        $mlm_distributor->setBankAccNo($this->getRequestParameter('bankAccountNo'));
        $mlm_distributor->setBankHolderName($this->getRequestParameter('bankHolderName'));
        $mlm_distributor->setParentId($parentId);
        $mlm_distributor->setParentCode($this->getRequestParameter('sponsorId'));
        $mlm_distributor->setTotalLeft(0);
        $mlm_distributor->setTotalRight(0);
        $mlm_distributor->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_distributor->save();

        $this->getUser()->setAttribute(Globals::SESSION_USERNAME, $fcode);

        /****************************/
        /*****  Send email **********/
        /****************************/
        error_reporting(E_STRICT);

        date_default_timezone_set(date_default_timezone_get());

        include_once('class.phpmailer.php');

        $subject = $this->getContext()->getI18N()->__("Tune International Group Registration email notification", null, 'email');
        $body = $this->getContext()->getI18N()->__("Dear %1%", array('%1%' => $mlm_distributor->getNickname()), 'email') . ",<p><p>

        <p>" . $this->getContext()->getI18N()->__("Your registration request has been successfully sent to Tune International Group", null, 'email') . "</p>
        <p><b>" . $this->getContext()->getI18N()->__("Shareholder ID", null) . ": " . $fcode . "</b>
        <p><b>" . $this->getContext()->getI18N()->__("Password", null) . ": " . $password . "</b>";

        $mail = new PHPMailer();
        $mail->IsMail(); // telling the class to use SMTP
        $mail->Host = Globals::EMAIL_HOST; // SMTP server
        $mail->Sender = Globals::EMAIL_FROM_NOREPLY;
        $mail->From = Globals::EMAIL_FROM_NOREPLY;
        $mail->FromName = Globals::EMAIL_FROM_NOREPLY_NAME;
        $mail->Subject = $subject;
        $mail->CharSet="utf-8";

        $text_body = $body;

        $mail->Body = $body;
        $mail->AltBody = $text_body;
        $mail->AddAddress($mlm_distributor->getEmail(), $mlm_distributor->getNickname());

        if (!$mail->Send()) {
            echo $mail->ErrorInfo;
        }
        return $this->redirect('/member/registerInfo');
    }

    public function executeVerifySponsorId()
    {
        $sponsorId = $this->getRequestParameter('sponsorId');

        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $existUser = MlmDistributorPeer::doSelectOne($c);

        $arr = "";
        if ($existUser) {
            //if ($existUser->getDistributorId() <> $this->getUser()->getAttribute(Globals::SESSION_DISTID)) {
            $arr = array(
                'userId' => $existUser->getDistributorId(),
                'userName' => $existUser->getDistributorCode(),
                'fullname' => $existUser->getFullName(),
                'nickname' => $existUser->getNickname()
            );
            //}
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeFetchPackage()
    {
        $c = new Criteria();
        $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_EPOINT);
        $c->add(MlmAccountPeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $account = MlmAccountPeer::doSelectOne($c);

        $c = new Criteria();
        $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
        $c->add(MlmAccountPeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $ecashAccount = MlmAccountPeer::doSelectOne($c);

        $arr = array(
            'packageId' => 0,
            'point' => 0,
            'ecash' => 0,
            'package' => ""
        );
        if (($account) && ($ecashAccount)) {
            $max = $ecashAccount->getBalance();

            if ($account->getBalance() > $ecashAccount->getBalance())
                $max = $account->getBalance();

            $c = new Criteria();
            $c->add(MlmPackagePeer::PRICE, $max, Criteria::LESS_EQUAL);
            $c->addDescendingOrderByColumn(MlmPackagePeer::PRICE);

            $packages = MlmPackagePeer::doSelect($c);

            $packageArray = array();
            $count = 0;
            foreach ($packages as $package) {
                $packageArray[$count]["packageId"] = $package->getPackageId();
                $packageArray[$count]["name"] = $this->getContext()->getI18N()->__($package->getPackageName());
                $packageArray[$count]["price"] = $package->getPrice();
                $count++;
            }

            $arr = array(
                'point' => $account->getBalance(),
                'ecash' => $ecashAccount->getBalance(),
                'package' => $packageArray
            );
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeSummary()
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::PARENT_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_PENDING);
        $this->TblDistributor = MlmDistributorPeer::doSelect($c);
    }

    public function executeAnnouncementList()
    {
        $sColumns = $this->getRequestParameter('sColumns');
        $aColumns = explode(",", $sColumns);

        $iColumns = $this->getRequestParameter('iColumns');

        $offset = $this->getRequestParameter('iDisplayStart');
        $sEcho = $this->getRequestParameter('sEcho');
        $limit = $this->getRequestParameter('iDisplayLength');
        $arr = array();

        /******   total records  *******/
        $c = new Criteria();
        $c->add(MlmAnnouncementPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $totalRecords = MlmAnnouncementPeer::doCount($c);

        /******   total filtered records  *******/
        /*if ($this->getRequestParameter('filterAction') != "") {
            $c->addAnd(MlmAnnouncementPeer::TRANSACTION_TYPE, "%" . $this->getRequestParameter('filterAction') . "%", Criteria::LIKE);
        }*/
        $totalFilteredRecords = MlmAnnouncementPeer::doCount($c);

        /******   sorting  *******/
        for ($i = 0; $i < intval($this->getRequestParameter('iSortingCols')); $i++)
        {
            if ($this->getRequestParameter('bSortable_' . intval($this->getRequestParameter('iSortCol_' . $i))) == "true") {
                if ("asc" == $this->getRequestParameter('sSortDir_' . $i)) {
                    $c->addAscendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                } else {
                    $c->addDescendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                }
            }
        }

        /******   pagination  *******/
        $pager = new sfPropelPager('MlmAnnouncement', $limit);
        $pager->setCriteria($c);
        $pager->setPage(($offset / $limit) + 1);
        $pager->init();

        foreach ($pager->getResults() as $result) {
            $title = $result->getTitle();
            $createdOn = $result->getCreatedOn();

            if ($this->getUser()->getCulture() == "cn") {
                $title = $result->getTitleCn();
                $createdOn = $result->getCreatedOn();
            }
            $arr[] = array(
                $result->getAnnouncementId(),
                $title,
                $createdOn
            );
        }

        $output = array(
            "sEcho" => intval($sEcho),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalFilteredRecords,
            "aaData" => $arr
        );
        echo json_encode($output);

        return sfView::HEADER_ONLY;
    }

    public function executeBonusDetailList()
    {
        $sColumns = $this->getRequestParameter('sColumns');
        $aColumns = explode(",", $sColumns);

        $iColumns = $this->getRequestParameter('iColumns');

        $offset = $this->getRequestParameter('iDisplayStart');
        $sEcho = $this->getRequestParameter('sEcho');
        $limit = $this->getRequestParameter('iDisplayLength');
        $arr = array();

        /******   total records  *******/
        $c = new Criteria();
        $c->add(MlmDistCommissionLedgerPeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $totalRecords = MlmDistCommissionLedgerPeer::doCount($c);

        /******   total filtered records  *******/
        if ($this->getRequestParameter('filterAction') != "") {
            $c->addAnd(MlmDistCommissionLedgerPeer::COMMISSION_TYPE, $this->getRequestParameter('filterAction'));
        }
        $totalFilteredRecords = MlmDistCommissionLedgerPeer::doCount($c);

        /******   sorting  *******/
        for ($i = 0; $i < intval($this->getRequestParameter('iSortingCols')); $i++)
        {
            if ($this->getRequestParameter('bSortable_' . intval($this->getRequestParameter('iSortCol_' . $i))) == "true") {
                if ("asc" == $this->getRequestParameter('sSortDir_' . $i)) {
                    $c->addAscendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                } else {
                    $c->addDescendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                }
            }
        }

        /******   pagination  *******/
        $pager = new sfPropelPager('MlmDistCommissionLedger', $limit);
        $pager->setCriteria($c);
        $pager->setPage(($offset / $limit) + 1);
        $pager->init();

        foreach ($pager->getResults() as $result) {
            $arr[] = array(
                $result->getCommissionId() == null ? "0" : $result->getCommissionId(),
                $result->getCreatedOn() == null ? "" : $result->getCreatedOn(),
                $result->getCommissionType() == null ? ""
                        : $this->getContext()->getI18N()->__($result->getCommissionType()),
                $result->getCredit() == null ? "0" : number_format($result->getCredit(), 2),
                $result->getDebit() == null ? "0" : number_format($result->getDebit(), 2),
                $result->getRemark() == null ? "" : $result->getRemark()
            );
        }

        $output = array(
            "sEcho" => intval($sEcho),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalFilteredRecords,
            "aaData" => $arr
        );
        echo json_encode($output);

        return sfView::HEADER_ONLY;
    }

    public function executeDelete()
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::PARENT_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_PENDING);
        $c->addAnd(MlmDistributorPeer::DISTRIBUTOR_ID, $this->getRequestParameter('distid'));
        $mlmDistributor = MlmDistributorPeer::doSelectOne($c);
        $this->forward404Unless($mlmDistributor);

        $mlmDistributor->setStatusCode(Globals::STATUS_CANCEL);
        $mlmDistributor->save();

        $appUser = AppUserPeer::retrieveByPk($mlmDistributor->getUserId());
        $this->forward404Unless($appUser);
        $appUser->setStatusCode(Globals::STATUS_CANCEL);
        $appUser->save();

        return $this->redirect('/member/summary');
    }

    public function executeVerifyTransactionPassword()
    {
        $c = new Criteria();
        $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
        $c->add(AppUserPeer::USERPASSWORD2, $this->getRequestParameter('transactionPassword'));
        $c->add(AppUserPeer::USER_ROLE, Globals::ROLE_DISTRIBUTOR);
        $c->add(AppUserPeer::STATUS_CODE, Globals::STATUS_ACTIVE);

        $existUser = AppUserPeer::doSelectOne($c);

        if ($existUser) {
            echo 'true';
        } else {
            echo 'false';
        }

        return sfView::HEADER_ONLY;
    }

    public function executeActivateMember()
    {
        $sponsorId = $this->getRequestParameter('sponsorId');
        $transactionPassword = $this->getRequestParameter('transactionPassword');
        $packageId = $this->getRequestParameter('packageId');
        $paymentType = $this->getRequestParameter('paymentType');

        $error = false;
        $errorMsg = "";

        $c = new Criteria();
        $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
        $c->add(AppUserPeer::USERPASSWORD2, $transactionPassword);
        $c->add(AppUserPeer::USER_ROLE, Globals::ROLE_DISTRIBUTOR);
        $c->add(AppUserPeer::STATUS_CODE, Globals::STATUS_ACTIVE);

        $existUser = AppUserPeer::doSelectOne($c);

        if (!$existUser) {
            $error = true;
            $errorMsg = "Invalid Transaction Password.";
        }

        $packageDB = null;
        if (!$error) {
            $packageDB = MlmPackagePeer::retrieveByPK($packageId);
            $this->forward404Unless($packageDB);
            if (!$packageDB) {
                $error = true;
                $errorMsg = "Invalid Package.";
            }
        }

        if (!$error) {
            if ("epoint" == $paymentType) {
                $c = new Criteria();
                $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_EPOINT);
                $c->add(MlmAccountPeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $account = MlmAccountPeer::doSelectOne($c);
                $this->forward404Unless($account);
                if (!$account) {
                    $error = true;
                    $errorMsg = "Invalid Action.";
                } else if ($account->getBalance() < $packageDB->getPrice()) {
                    $error = true;
                    $errorMsg = "Insufficient e-Points.";
                }
            } else if ("ecash" == $paymentType) {
                $c = new Criteria();
                $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
                $c->add(MlmAccountPeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $account = MlmAccountPeer::doSelectOne($c);
                $this->forward404Unless($account);
                if (!$account) {
                    $error = true;
                    $errorMsg = "Invalid Action.";
                } else if ($account->getBalance() < $packageDB->getPrice()) {
                    $error = true;
                    $errorMsg = "Insufficient e-Points.";
                }
            } else {
                $error = true;
                $errorMsg = "Invalid Action.";
            }
        }

        if (!$error) {
            //if ("epoint" == $paymentType) {
            $this->doActivateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), $sponsorId, $packageId, $paymentType);
            //} else if ("ecash" == $paymentType) {
            //$this->doActivateAccountByEcash($this->getUser()->getAttribute(Globals::SESSION_DISTID), $sponsorId, $packageId);
            //}
        }
        $arr = array(
            'error' => $error
        , 'errorMsg' => $errorMsg
        );
        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executePlacementTree()
    {
        if ($this->getRequestParameter('doAction') == "save") {
            $uplineDistCode = $this->getRequestParameter('uplineDistCode');
            $uplinePosition = $this->getRequestParameter('uplinePosition');
            $sponsorDistId = $this->getRequestParameter('sponsorDistId');

            $uplineDistDB = $this->getDistributorInformation($uplineDistCode);
            $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $sponsorDB = MlmDistributorPeer::retrieveByPk($sponsorDistId);
            $this->forward404Unless($distDB);
            $this->forward404Unless($sponsorDB);

            $treeStructure = $uplineDistDB->getTreeStructure() . "|" . $sponsorDB->getDistributorCode() . "|";
            $treeLevel = $uplineDistDB->getTreeLevel() + 1;

            $sponsorDB->setPlacementDatetime(date("Y/m/d h:i:s A"));
            $sponsorDB->setPlacementPosition($uplinePosition);
            $sponsorDB->setUplineDistId($uplineDistDB->getDistributorId());
            $sponsorDB->setUplineDistCode($uplineDistDB->getDistributorCode());
            $sponsorDB->setTreeStructure($treeStructure);
            $sponsorDB->setTreeLevel($treeLevel);
            $sponsorDB->setParentId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $sponsorDB->setParentCode($this->getUser()->getAttribute(Globals::SESSION_USERNAME));
            $sponsorDB->save();

            $sponsoredPackageDB = MlmPackagePeer::retrieveByPK($sponsorDB->getRankId());
            $this->forward404Unless($sponsoredPackageDB);
            $pairingPoint = $sponsoredPackageDB->getPrice();

            // recalculate Total left and total right for $uplineDistDB
            $arrs = explode("|", $uplineDistDB->getTreeStructure());
            for ($x = count($arrs); $x > 0; $x--) {
                if ($arrs[$x] == "") {
                    continue;
                }
                $uplineDistDB = $this->getDistributorInformation($arrs[$x]);
                $this->forward404Unless($uplineDistDB);
                $totalLeft = $this->getTotalPosition($arrs[$x], Globals::PLACEMENT_LEFT);
                $totalRight = $this->getTotalPosition($arrs[$x], Globals::PLACEMENT_RIGHT);
                $uplineDistDB->setTotalLeft($totalLeft);
                $uplineDistDB->setTotalRight($totalRight);
                $uplineDistDB->save();
            }

            /******************************/
            /*  store Pairing points
            /******************************/
            if ($sponsorDB->getUplineDistId() != 0 && $sponsorDB->getUplineDistCode() != null) {
                $level = 0;
                $uplineDistDB = MlmDistributorPeer::retrieveByPk($sponsorDB->getUplineDistId());
                $sponsoredDistributorCode = $sponsorDB->getDistributorCode();
                while ($level < 200) {
                    //var_dump($uplineDistDB->getUplineDistId());
                    //var_dump($uplineDistDB->getUplineDistCode());
                    //print_r("<br>");
                    $c = new Criteria();
                    $c->add(MlmDistPairingPeer::DIST_ID, $uplineDistDB->getDistributorId());
                    $sponsorDistPairingDB = MlmDistPairingPeer::doSelectOne($c);

                    $addToLeft = 0;
                    $addToRight = 0;
                    $leftBalance = 0;
                    $rightBalance = 0;
                    if (!$sponsorDistPairingDB) {
                        $sponsorDistPairingDB = new MlmDistPairing();
                        $sponsorDistPairingDB->setDistId($uplineDistDB->getDistributorId());

                        $packageDB = MlmPackagePeer::retrieveByPK($uplineDistDB->getRankId());
                        $this->forward404Unless($packageDB);

                        $sponsorDistPairingDB->setLeftBalance($leftBalance);
                        $sponsorDistPairingDB->setRightBalance($rightBalance);
                        $sponsorDistPairingDB->setFlushLimit($packageDB->getDailyMaxPairing());
                        $sponsorDistPairingDB->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    } else {
                        $leftBalance = $sponsorDistPairingDB->getLeftBalance();
                        $rightBalance = $sponsorDistPairingDB->getRightBalance();
                    }
                    $sponsorDistPairingDB->setLeftBalance($leftBalance + $addToLeft);
                    $sponsorDistPairingDB->setRightBalance($rightBalance + $addToRight);
                    $sponsorDistPairingDB->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $sponsorDistPairingDB->save();

                    $c = new Criteria();
                    $c->add(MlmDistPairingLedgerPeer::DIST_ID, $uplineDistDB->getDistributorId());
                    $c->add(MlmDistPairingLedgerPeer::LEFT_RIGHT, $uplinePosition);
                    $c->addDescendingOrderByColumn(MlmDistPairingLedgerPeer::CREATED_ON);
                    $sponsorDistPairingLedgerDB = MlmDistPairingLedgerPeer::doSelectOne($c);

                    $legBalance = 0;
                    if ($sponsorDistPairingLedgerDB) {
                        $legBalance = $sponsorDistPairingLedgerDB->getBalance();
                    }

                    $sponsorDistPairingledger = new MlmDistPairingLedger();
                    $sponsorDistPairingledger->setDistId($uplineDistDB->getDistributorId());
                    $sponsorDistPairingledger->setLeftRight($uplinePosition);
                    $sponsorDistPairingledger->setTransactionType(Globals::PAIRING_LEDGER_REGISTER);
                    $sponsorDistPairingledger->setCredit($pairingPoint);
                    $sponsorDistPairingledger->setDebit(0);
                    $sponsorDistPairingledger->setBalance($legBalance + $pairingPoint);
                    $sponsorDistPairingledger->setRemark("PAIRING POINT AMOUNT (" . $sponsoredDistributorCode . ")");
                    $sponsorDistPairingledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $sponsorDistPairingledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $sponsorDistPairingledger->save();

                    $this->revalidatePairing($uplineDistDB->getDistributorId(), $uplinePosition);

                    if ($uplineDistDB->getUplineDistId() == 0 || $uplineDistDB->getUplineDistCode() == null) {
                        break;
                    }

                    $uplinePosition = $uplineDistDB->getPlacementPosition();
                    $uplineDistDB = MlmDistributorPeer::retrieveByPk($uplineDistDB->getUplineDistId());
                    $level++;
                }
            }
            /******************************/
            /*  Pairing             ~ END ~
            /******************************/
            return $this->redirect('/member/placementTree?distcode=' . $this->getRequestParameter('distcode', $this->getUser()->getAttribute(Globals::SESSION_USERNAME)));
        }
        $distcode = $this->getRequestParameter('distcode', $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
        $anode = array();
        //      0
        //  1       2
        //3   4   5   6

        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $distcode);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%|" . $this->getUser()->getAttribute(Globals::SESSION_USERNAME) . "|%", Criteria::LIKE);
        $distDB = MlmDistributorPeer::doSelectOne($c);

        if (!$distDB) {
            $this->errorSearch = true;
            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
            $distDB = MlmDistributorPeer::doSelectOne($c);
        }

        $leftOnePlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
        $rightTwoPlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
        $anode[0]["distCode"] = $distDB->getDistributorCode();
        $anode[0]["_self"] = $distDB;
        $anode[0]["_left"] = $leftOnePlacement;
        $anode[0]["_right"] = $rightTwoPlacement;
        $anode[0]["_available"] = false;
        $anode[0]["_left_this_month_sales"] = $this->getThisMonthSales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
        $anode[0]["_right_this_month_sales"] = $this->getThisMonthSales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
        $anode[0]["_dist_pairing_ledger"] = $this->queryDistPairing($distDB->getDistributorId());

        if ($leftOnePlacement == null) {
            $anode[1]["distCode"] = "";
            $anode[1]["_self"] = new MlmDistributor();
            $anode[1]["_left"] = null;
            $anode[1]["_right"] = null;
            $anode[1]["_available"] = true;
            $anode[1]["_left_this_month_sales"] = null;
            $anode[1]["_right_this_month_sales"] = null;
            $anode[1]["_dist_pairing_ledger"] = null;

            $anode[3]["distCode"] = "";
            $anode[3]["_self"] = new MlmDistributor();
            $anode[3]["_left"] = null;
            $anode[3]["_right"] = null;
            $anode[3]["_available"] = false;
            $anode[3]["_left_this_month_sales"] = null;
            $anode[3]["_right_this_month_sales"] = null;
            $anode[3]["_dist_pairing_ledger"] = null;

            $anode[4]["distCode"] = "";
            $anode[4]["_self"] = new MlmDistributor();
            $anode[4]["_left"] = null;
            $anode[4]["_right"] = null;
            $anode[4]["_available"] = false;
            $anode[4]["_left_this_month_sales"] = null;
            $anode[4]["_right_this_month_sales"] = null;
            $anode[4]["_dist_pairing_ledger"] = null;
        } else {
            $distDB = $this->getDistributorInformation($leftOnePlacement->getDistributorCode());
            $leftThreePlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
            $rightFourPlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);

            $anode[1]["distCode"] = $leftOnePlacement->getDistributorCode();
            $anode[1]["_self"] = $distDB;
            $anode[1]["_left"] = $leftThreePlacement;
            $anode[1]["_right"] = $rightFourPlacement;
            $anode[1]["_available"] = false;
            $anode[1]["_left_this_month_sales"] = $this->getThisMonthSales($leftOnePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
            $anode[1]["_right_this_month_sales"] = $this->getThisMonthSales($leftOnePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
            $anode[1]["_dist_pairing_ledger"] = $this->queryDistPairing($leftOnePlacement->getDistributorId());

            if ($leftThreePlacement == null) {
                $anode[3]["distCode"] = "";
                $anode[3]["_self"] = new MlmDistributor();
                $anode[3]["_left"] = null;
                $anode[3]["_right"] = null;
                $anode[3]["_available"] = true;
                $anode[3]["_left_this_month_sales"] = null;
                $anode[3]["_right_this_month_sales"] = null;
                $anode[3]["_dist_pairing_ledger"] = null;
            } else {
                $distDB = $this->getDistributorInformation($leftThreePlacement->getDistributorCode());
                $anode[3]["distCode"] = $leftThreePlacement->getDistributorCode();
                $anode[3]["_self"] = $distDB;
                $anode[3]["_left"] = null;
                $anode[3]["_right"] = null;
                $anode[3]["_available"] = false;
                $anode[3]["_left_this_month_sales"] = $this->getThisMonthSales($leftThreePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[3]["_right_this_month_sales"] = $this->getThisMonthSales($leftThreePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[3]["_dist_pairing_ledger"] = $this->queryDistPairing($leftThreePlacement->getDistributorId());
            }
            if ($rightFourPlacement == null) {
                $anode[4]["distCode"] = "";
                $anode[4]["_self"] = new MlmDistributor();
                $anode[4]["_left"] = null;
                $anode[4]["_right"] = null;
                $anode[4]["_available"] = true;
                $anode[4]["_left_this_month_sales"] = null;
                $anode[4]["_right_this_month_sales"] = null;
                $anode[4]["_dist_pairing_ledger"] = null;
            } else {
                $distDB = $this->getDistributorInformation($rightFourPlacement->getDistributorCode());
                $anode[4]["distCode"] = $rightFourPlacement->getDistributorCode();
                $anode[4]["_self"] = $distDB;
                $anode[4]["_left"] = null;
                $anode[4]["_right"] = null;
                $anode[4]["_available"] = false;
                $anode[4]["_left_this_month_sales"] = $this->getThisMonthSales($rightFourPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[4]["_right_this_month_sales"] = $this->getThisMonthSales($rightFourPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[4]["_dist_pairing_ledger"] = $this->queryDistPairing($rightFourPlacement->getDistributorId());
            }
        }
        if ($rightTwoPlacement == null) {
            $anode[2]["distCode"] = "";
            $anode[2]["_self"] = new MlmDistributor();
            $anode[2]["_left"] = null;
            $anode[2]["_right"] = null;
            $anode[2]["_available"] = true;
            $anode[2]["_left_this_month_sales"] = null;
            $anode[2]["_right_this_month_sales"] = null;
            $anode[2]["_dist_pairing_ledger"] = null;

            $anode[5]["distCode"] = "";
            $anode[5]["_self"] = new MlmDistributor();
            $anode[5]["_left"] = null;
            $anode[5]["_right"] = null;
            $anode[5]["_available"] = false;
            $anode[5]["_left_this_month_sales"] = null;
            $anode[5]["_right_this_month_sales"] = null;
            $anode[5]["_dist_pairing_ledger"] = null;

            $anode[6]["distCode"] = "";
            $anode[6]["_self"] = new MlmDistributor();
            $anode[6]["_left"] = null;
            $anode[6]["_right"] = null;
            $anode[6]["_available"] = false;
            $anode[6]["_left_this_month_sales"] = null;
            $anode[6]["_right_this_month_sales"] = null;
            $anode[6]["_dist_pairing_ledger"] = null;
        } else {
            $distDB = $this->getDistributorInformation($rightTwoPlacement->getDistributorCode());
            $leftFivePlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
            $rightSixPlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);

            $anode[2]["distCode"] = $rightTwoPlacement->getDistributorCode();
            $anode[2]["_self"] = $distDB;
            $anode[2]["_left"] = $leftFivePlacement;
            $anode[2]["_right"] = $rightSixPlacement;
            $anode[2]["_available"] = false;
            $anode[2]["_left_this_month_sales"] = $this->getThisMonthSales($rightTwoPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
            $anode[2]["_right_this_month_sales"] = $this->getThisMonthSales($rightTwoPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
            $anode[2]["_dist_pairing_ledger"] = $this->queryDistPairing($rightTwoPlacement->getDistributorId());

            if ($leftFivePlacement == null) {
                $anode[5]["distCode"] = "";
                $anode[5]["_self"] = new MlmDistributor();
                $anode[5]["_left"] = null;
                $anode[5]["_right"] = null;
                $anode[5]["_available"] = true;
                $anode[5]["_left_this_month_sales"] = null;
                $anode[5]["_right_this_month_sales"] = null;
                $anode[5]["_dist_pairing_ledger"] = null;
            } else {
                $distDB = $this->getDistributorInformation($leftFivePlacement->getDistributorCode());
                $anode[5]["distCode"] = $leftFivePlacement->getDistributorCode();
                $anode[5]["_self"] = $distDB;
                $anode[5]["_left"] = null;
                $anode[5]["_right"] = null;
                $anode[5]["_available"] = false;
                $anode[5]["_left_this_month_sales"] = $this->getThisMonthSales($leftFivePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[5]["_right_this_month_sales"] = $this->getThisMonthSales($leftFivePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[5]["_dist_pairing_ledger"] = $this->queryDistPairing($leftFivePlacement->getDistributorId());
            }
            if ($rightSixPlacement == null) {
                $anode[6]["distCode"] = "";
                $anode[6]["_self"] = new MlmDistributor();
                $anode[6]["_left"] = null;
                $anode[6]["_right"] = null;
                $anode[6]["_available"] = true;
                $anode[6]["_left_this_month_sales"] = null;
                $anode[6]["_right_this_month_sales"] = null;
                $anode[6]["_dist_pairing_ledger"] = null;
            } else {
                $distDB = $this->getDistributorInformation($rightSixPlacement->getDistributorCode());
                $anode[6]["distCode"] = $rightSixPlacement->getDistributorCode();
                $anode[6]["_self"] = $distDB;
                $anode[6]["_left"] = null;
                $anode[6]["_right"] = null;
                $anode[6]["_available"] = false;
                $anode[6]["_left_this_month_sales"] = $this->getThisMonthSales($rightSixPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[6]["_right_this_month_sales"] = $this->getThisMonthSales($rightSixPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[6]["_dist_pairing_ledger"] = $this->queryDistPairing($rightSixPlacement->getDistributorId());
            }
        }

        $this->distcode = $distcode;
        $this->anode = $anode;
    }

    public function executePendingMemberList()
    {
        $sColumns = $this->getRequestParameter('sColumns');
        $aColumns = explode(",", $sColumns);

        $iColumns = $this->getRequestParameter('iColumns');

        $offset = $this->getRequestParameter('iDisplayStart');
        $sEcho = $this->getRequestParameter('sEcho');
        $limit = $this->getRequestParameter('iDisplayLength');
        $arr = array();

        /******   total records  *******/
        $c = new Criteria();
        $c->add(MlmDistributorPeer::PARENT_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $c->add(MlmDistributorPeer::TREE_LEVEL, null, Criteria::ISNULL);
        $c->add(MlmDistributorPeer::UPLINE_DIST_ID, null, Criteria::ISNULL);
        $c->add(MlmDistributorPeer::TREE_STRUCTURE, null, Criteria::ISNULL);
        $totalRecords = MlmDistributorPeer::doCount($c);

        /******   total filtered records  *******/
        if ($this->getRequestParameter('filterFullname') != "") {
            $c->addAnd(MlmDistributorPeer::FULL_NAME, "%" . $this->getRequestParameter('filterFullname') . "%", Criteria::LIKE);
        }
        if ($this->getRequestParameter('filterNickname') != "") {
            $c->addAnd(MlmDistributorPeer::NICKNAME, "%" . $this->getRequestParameter('filterNickname') . "%", Criteria::LIKE);
        }
        $totalFilteredRecords = MlmDistributorPeer::doCount($c);

        /******   sorting  *******/
        for ($i = 0; $i < intval($this->getRequestParameter('iSortingCols')); $i++)
        {
            if ($this->getRequestParameter('bSortable_' . intval($this->getRequestParameter('iSortCol_' . $i))) == "true") {
                if ("asc" == $this->getRequestParameter('sSortDir_' . $i)) {
                    $c->addAscendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                } else {
                    $c->addDescendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                }
            }
        }

        /******   pagination  *******/
        $pager = new sfPropelPager('MlmDistributor', $limit);
        $pager->setCriteria($c);
        $pager->setPage(($offset / $limit) + 1);
        $pager->init();

        foreach ($pager->getResults() as $result) {
            $arr[] = array(
                $result->getDistributorId() == null ? "" : $result->getDistributorId(),
                $result->getDistributorId() == null ? "" : $result->getDistributorId(),
                $result->getDistributorCode() == null ? "" : $result->getDistributorCode(),
                $result->getFullName() == null ? "" : $result->getFullName(),
                $result->getNickname() == null ? "" : $result->getNickname(),
                $result->getIc() == null ? "" : $result->getIc(),
                $result->getRankCode() == null ? "" : $result->getRankCode(),
                $result->getCreatedOn() == null ? "" : $result->getCreatedOn()
            );
        }
        $output = array(
            "sEcho" => intval($sEcho),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalFilteredRecords,
            "aaData" => $arr
        );
        echo json_encode($output);

        return sfView::HEADER_ONLY;
    }

    public function executeTransferEcash()
    {
        $ledgerAccountBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        $this->ledgerAccountBalance = $ledgerAccountBalance;

        $processFee = 0;
        $c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_TRANSFER_PROCESS_FEE);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB) {
            $processFee = $settingDB->getSettingValue();
        }
        $this->processFee = $processFee;

        if ($this->getRequestParameter('sponsorId') <> "" && $this->getRequestParameter('ecashAmount') > 0 && $this->getRequestParameter('transactionPassword') <> "") {
            $appUser = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

            $todayDateMonth = date('m');

            if ($todayDateMonth >= 6 && $this->getRequestParameter('ecashAmount') < 1000) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("e-Cash Transfer only accepted 1,000 USD or more."));
            } else {
                if (($this->getRequestParameter('ecashAmount') + $processFee) > $ledgerAccountBalance) {

                    $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient E-Cash Amount"));

                } elseif ($appUser->getUserPassword2() <> $this->getRequestParameter('transactionPassword')) {

                    $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid trx password"));

                } elseif (strtoupper($this->getRequestParameter('sponsorId')) == $this->getUser()->getAttribute(Globals::SESSION_USERNAME)) {

                    $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("You are not allow to transfer to own account."));

                } elseif ($this->getRequestParameter('sponsorId') <> "" && $this->getRequestParameter('ecashAmount') > 0) {

                    $c = new Criteria();
                    $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $this->getRequestParameter('sponsorId'));
                    $existDist = MlmDistributorPeer::doSelectOne($c);

                    $c = new Criteria();
                    $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
                    $c->addAnd(MlmAccountPeer::DIST_ID, $existDist->getDistributorId());
                    $toAccount = MlmAccountPeer::doSelectOne($c);

                    $toId = $existDist->getDistributorId();
                    $toCode = $existDist->getDistributorCode();
                    $toName = $existDist->getNickname();
                    $toBalance = $toAccount->getBalance();
                    $fromId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);
                    $fromCode = $this->getUser()->getAttribute(Globals::SESSION_USERNAME);
                    $fromName = $this->getUser()->getAttribute(Globals::SESSION_NICKNAME);
                    $fromBalance = $ledgerAccountBalance;

                    $mlm_account_ledger = new MlmAccountLedger();
                    $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                    $mlm_account_ledger->setDistId($fromId);
                    $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO);
                    $mlm_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO . " " . $toCode . " (" . $toName . ")");
                    $mlm_account_ledger->setCredit(0);
                    $mlm_account_ledger->setDebit($this->getRequestParameter('ecashAmount'));
                    $mlm_account_ledger->setBalance($fromBalance - $this->getRequestParameter('ecashAmount'));
                    $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlm_account_ledger->save();

                    $this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_ECASH);

                    $tbl_account_ledger = new MlmAccountLedger();
                    $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                    $tbl_account_ledger->setDistId($toId);
                    $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_FROM);
                    $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_FROM . " " . $fromCode . " (" . $fromName . ")");
                    $tbl_account_ledger->setCredit($this->getRequestParameter('ecashAmount'));
                    $tbl_account_ledger->setDebit(0);
                    $tbl_account_ledger->setBalance($toBalance + $this->getRequestParameter('ecashAmount'));
                    $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $tbl_account_ledger->save();

                    $this->revalidateAccount($toId, Globals::ACCOUNT_TYPE_ECASH);

                    // ******       processing fees      ****************
                    $tbl_account_ledger = new MlmAccountLedger();
                    $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                    $tbl_account_ledger->setDistId($fromId);
                    $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_PROCESS_CHARGE);
                    $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO . " " . $toCode . " (" . $toName . ") PROCESS CHARGES");
                    $tbl_account_ledger->setCredit(0);
                    $tbl_account_ledger->setDebit($processFee);
                    $tbl_account_ledger->setBalance($fromBalance - ($this->getRequestParameter('ecashAmount') + $processFee));
                    $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $tbl_account_ledger->save();

                    $this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_ECASH);

                    // ******       company account      ****************
                    $c = new Criteria();
                    $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
                    $c->addAnd(MlmAccountPeer::DIST_ID, Globals::SYSTEM_COMPANY_DIST_ID);
                    $companyAccount = MlmAccountPeer::doSelectOne($c);

                    $tbl_account_ledger = new MlmAccountLedger();
                    $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                    $tbl_account_ledger->setDistId(Globals::SYSTEM_COMPANY_DIST_ID);
                    $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER);
                    $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_PROCESS_CHARGE . " " . $fromCode . " -> " . $toCode);
                    $tbl_account_ledger->setCredit($processFee);
                    $tbl_account_ledger->setDebit(0);
                    $tbl_account_ledger->setBalance($companyAccount->getBalance() + $processFee);
                    $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $tbl_account_ledger->save();

                    $this->revalidateAccount(Globals::SYSTEM_COMPANY_DIST_ID, Globals::ACCOUNT_TYPE_ECASH);

                    $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Transfer success"));

                    return $this->redirect('/member/transferEcash');
                }
            }
        }
    }

    public function executeTransferEpoint()
    {
        $c = new Criteria();
        $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_EPOINT);
        $c->addAnd(MlmAccountPeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $mlmAccount = MlmAccountPeer::doSelectOne($c);
        $this->mlmAccount = $mlmAccount;

        $processFee = 0;
        /*$c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_TRANSFER_PROCESS_FEE);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB)
            $processFee = $settingDB->getSettingValue();*/
        $this->processFee = $processFee;

        if ($this->getRequestParameter('sponsorId') <> "" && $this->getRequestParameter('epointAmount') > 0 && $this->getRequestParameter('transactionPassword') <> "") {
            $appUser = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

            if (($this->getRequestParameter('epointAmount') + $processFee) > $mlmAccount->getBalance()) {

                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient E-Point Amount"));

            } elseif ($appUser->getUserPassword2() <> $this->getRequestParameter('transactionPassword')) {

                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid trx password"));

            } elseif (strtoupper($this->getRequestParameter('sponsorId')) == $this->getUser()->getAttribute(Globals::SESSION_USERNAME)) {

                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("You are not allow to transfer to own account."));

            } elseif ($this->getRequestParameter('sponsorId') <> "" && $this->getRequestParameter('epointAmount') > 0) {

                $c = new Criteria();
                $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $this->getRequestParameter('sponsorId'));
                $existDist = MlmDistributorPeer::doSelectOne($c);

                $c = new Criteria();
                $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_EPOINT);
                $c->addAnd(MlmAccountPeer::DIST_ID, $existDist->getDistributorId());
                $toAccount = MlmAccountPeer::doSelectOne($c);

                $toId = $existDist->getDistributorId();
                $toCode = $existDist->getDistributorCode();
                $toName = $existDist->getNickname();
                $toBalance = $toAccount->getBalance();
                $fromId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);
                $fromCode = $this->getUser()->getAttribute(Globals::SESSION_USERNAME);
                $fromName = $this->getUser()->getAttribute(Globals::SESSION_NICKNAME);
                $fromBalance = $mlmAccount->getBalance();

                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $mlm_account_ledger->setDistId($fromId);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO);
                $mlm_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO . " " . $toCode . " (" . $toName . ")");
                $mlm_account_ledger->setCredit(0);
                $mlm_account_ledger->setDebit($this->getRequestParameter('epointAmount'));
                $mlm_account_ledger->setBalance($fromBalance - $this->getRequestParameter('epointAmount'));
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                $this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_EPOINT);

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $tbl_account_ledger->setDistId($toId);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_FROM);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_FROM . " " . $fromCode . " (" . $fromName . ")");
                $tbl_account_ledger->setCredit($this->getRequestParameter('epointAmount'));
                $tbl_account_ledger->setDebit(0);
                $tbl_account_ledger->setBalance($toBalance + $this->getRequestParameter('epointAmount'));
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $this->revalidateAccount($toId, Globals::ACCOUNT_TYPE_EPOINT);

                // ******       processing fees      ****************
                /*$tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $tbl_account_ledger->setDistId($fromId);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_PROCESS_CHARGE);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO . " " . $toCode . " (" . $toName . ") PROCESS CHARGES");
                $tbl_account_ledger->setCredit(0);
                $tbl_account_ledger->setDebit($processFee);
                $tbl_account_ledger->setBalance($fromBalance - ($this->getRequestParameter('epointAmount') + $processFee));
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_EPOINT);*/

                // ******       company account      ****************
                /*$c = new Criteria();
                $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_EPOINT);
                $c->addAnd(MlmAccountPeer::DIST_ID, Globals::SYSTEM_COMPANY_DIST_ID);
                $companyAccount = MlmAccountPeer::doSelectOne($c);

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $tbl_account_ledger->setDistId(Globals::SYSTEM_COMPANY_DIST_ID);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_PROCESS_CHARGE . " " . $fromCode . " -> " . $toCode);
                $tbl_account_ledger->setCredit($processFee);
                $tbl_account_ledger->setDebit(0);
                $tbl_account_ledger->setBalance($companyAccount->getBalance() + $processFee);
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $this->revalidateAccount(Globals::SYSTEM_COMPANY_DIST_ID, Globals::ACCOUNT_TYPE_EPOINT);*/

                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Transfer success"));
                return $this->redirect('/member/transferEpoint');
                /*$c = new Criteria();
                $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_EPOINT);
                $c->addAnd(MlmAccountPeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $mlmAccount = MlmAccountPeer::doSelectOne($c);
                $this->mlmAccount = $mlmAccount;*/
            }
        }
    }

    public function executeEcashLog()
    {
    }

    public function executeMaintenanceLog()
    {
    }

    public function executeEpointLog()
    {
    }

    public function executeFetchAnnouncementById()
    {
        $arr = "";
        if ($this->getRequestParameter('announcementId') <> "") {
            $announcement = MlmAnnouncementPeer::retrieveByPk($this->getRequestParameter('announcementId'));

            if ($announcement) {
                $title = $announcement->getTitle();
                $content = $announcement->getContent();
                if ($this->getUser()->getCulture() == 'cn') {
                    $title = $announcement->getTitleCn();
                    $content = $announcement->getContentCn();
                }
                $arr = array(
                    'title' => $title,
                    'content' => $content
                );
            }
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeLoginPassword()
    {
        if ($this->getRequestParameter('oldPassword')) {
            $c = new Criteria();
            $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
            $exist = AppUserPeer::doSelectOne($c);

            if ($exist->getUserpassword() <> $this->getRequestParameter('oldPassword')) {
                $this->setFlash('errorMsg', "Invalid password");
            } else {
                $exist->setUserpassword($this->getRequestParameter('newPassword'));
                $exist->setKeepPassword($this->getRequestParameter('newPassword'));
                $exist->save();
                $this->setFlash('successMsg', "Password updated");
            }
            return $this->redirect('/member/loginPassword');
        }
    }

    public function executeTransactionPassword()
    {
        if ($this->getRequestParameter('oldPassword')) {
            $c = new Criteria();
            $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
            $exist = AppUserPeer::doSelectOne($c);

            if ($exist->getUserpassword2() <> $this->getRequestParameter('oldPassword')) {
                $this->setFlash('errorMsg', "Invalid trx password");
            } else {
                $exist->setUserpassword2($this->getRequestParameter('newPassword'));
                $exist->setKeepPassword2($this->getRequestParameter('newPassword'));
                $exist->save();
                $this->setFlash('successMsg', "Trx Password updated");
            }
            return $this->redirect('/member/transactionPassword');
        }
    }

    public function executeAnnouncement()
    {
    }

    public function executeSponsorTree()
    {
        $id = $this->getUser()->getAttribute(Globals::SESSION_DISTID);
        $distinfo = MlmDistributorPeer::retrieveByPk($id);
        $this->distinfo = $distinfo;
        $this->hasChild = $this->checkHasChild($distinfo->getDistributorId());
    }

    public function executeManipulateSponsorTree()
    {
        $parentId = $this->getRequestParameter('root');
        $arrTree = array();
        if ($parentId != "") {
            $c = new Criteria();
            $c->add(MlmDistributorPeer::PARENT_ID, $parentId);
            $c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $dists = MlmDistributorPeer::doSelect($c);

            $idx = 0;
            foreach ($dists as $dist)
            {
                $arrTree[$idx]["text"] = $dist->getDistributorCode() . " " . $dist->getNickName() . " Joined " . date('Y-m-d', strtotime($dist->getActiveDatetime()));
                $arrTree[$idx]["id"] = $dist->getDistributorId();
                $arrTree[$idx]["hasChildren"] = $this->checkHasChild($dist->getDistributorId());
                $idx++;
            }
        }


        echo json_encode($arrTree);
        return sfView::HEADER_ONLY;
    }

    public function executeEcashWithdrawal()
    {
        $ledgerAccountBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        $this->ledgerAccountBalance = $ledgerAccountBalance;

        $withdrawAmount = $this->getRequestParameter('ecashAmount') * 1.05;
        $processFee = $this->getRequestParameter('ecashAmount') * 0.05;

        $dateUtil = new DateUtil();
        $currentDate = $dateUtil->formatDate("Y-m-d", date("Y-m-d"));
        $alreadyWithdraw = $this->findDailyWithdrawal($this->getUser()->getAttribute(Globals::SESSION_DISTID), $currentDate);

        $maxWithdrawal = floor($ledgerAccountBalance / 2);
        $this->maxWithdrawal = $maxWithdrawal;

        if ($this->getRequestParameter('ecashAmount') > 0 && $this->getRequestParameter('transactionPassword') <> "") {
            $tbl_user = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

            $dailyWithdrawal = $this->getRequestParameter('ecashAmount') + $alreadyWithdraw;
            if ($withdrawAmount > $ledgerAccountBalance) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient E-Cash"));

            } elseif (($ledgerAccountBalance/2) < $this->getRequestParameter('ecashAmount')) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Amount of withdrawal requested MUST BE TWICE of amount of E-cash available in Wallet."));

            } elseif ($dailyWithdrawal > 5000) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Maximum daily withdrawal is USD 5000"));

            } elseif ($tbl_user->getUserpassword2() <> $this->getRequestParameter('transactionPassword')) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid trx password"));

            } elseif ($withdrawAmount > 0) {
                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL);
                $tbl_account_ledger->setCredit(0);
                $tbl_account_ledger->setDebit($this->getRequestParameter('ecashAmount'));
                $tbl_account_ledger->setBalance($ledgerAccountBalance - $this->getRequestParameter('ecashAmount'));
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $accountLedgerId = $tbl_account_ledger->getAccountId();
                // ******       processing fees      ****************
                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_PROCESS_CHARGE);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL);
                $tbl_account_ledger->setCredit(0);
                $tbl_account_ledger->setDebit($processFee);
                $tbl_account_ledger->setBalance($ledgerAccountBalance - ($this->getRequestParameter('ecashAmount') + $processFee));
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();
                $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);

                // ******       company account      ****************
                $c = new Criteria();
                $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
                $c->addAnd(MlmAccountPeer::DIST_ID, Globals::SYSTEM_COMPANY_DIST_ID);
                $companyAccount = MlmAccountPeer::doSelectOne($c);

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId(Globals::SYSTEM_COMPANY_DIST_ID);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL . " " . $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
                $tbl_account_ledger->setCredit($processFee);
                $tbl_account_ledger->setDebit(0);
                $tbl_account_ledger->setBalance($companyAccount->getBalance() + $processFee);
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $this->revalidateAccount(Globals::SYSTEM_COMPANY_DIST_ID, Globals::ACCOUNT_TYPE_ECASH);


                $tbl_ecash_withdraw = new MlmEcashWithdraw();
                $tbl_ecash_withdraw->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $tbl_ecash_withdraw->setAccountLedgerId($accountLedgerId);
                $tbl_ecash_withdraw->setDeduct($this->getRequestParameter('ecashAmount'));
                $tbl_ecash_withdraw->setAmount($withdrawAmount);
                $tbl_ecash_withdraw->setStatusCode(Globals::WITHDRAWAL_PENDING);
                $tbl_ecash_withdraw->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_ecash_withdraw->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_ecash_withdraw->save();

                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Withdraw success"));

                /****************************/
                /*****  Send email **********/
                /****************************/
                error_reporting(E_STRICT);

                date_default_timezone_set(date_default_timezone_get());

                include_once('class.phpmailer.php');

                $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $subject = $this->getContext()->getI18N()->__("Tune International Group Withdrawal email notification", null, 'email');
                $body = "Dear Boss,<p><p>

                <p>Distributor Code : ". $distDB->getDistributorCode() .
                "<p>Withdrawal Amount : ".  $this->getRequestParameter('ecashAmount') .
                "<p>Date : " .  date("Y/m/d h:i:s A");
                //                "<p>Tree : ".  $distDB->getTreeStructure() .

                $mail = new PHPMailer();
                $mail->IsMail(); // telling the class to use SMTP
                $mail->Host = Globals::EMAIL_HOST; // SMTP server
                $mail->Sender = Globals::EMAIL_FROM_NOREPLY;
                $mail->From = Globals::EMAIL_FROM_NOREPLY;
                $mail->FromName = Globals::EMAIL_FROM_NOREPLY_NAME;
                $mail->Subject = $subject;
                $mail->CharSet="utf-8";

                $text_body = $body;

                $mail->Body = $body;
                $mail->AltBody = $text_body;
                //$mail->AddAddress($mlm_distributor->getEmail(), $mlm_distributor->getNickname());
                $mail->AddAddress("r9projecthost@gmail.com", "r9projecthost");

                if (!$mail->Send()) {
                    echo $mail->ErrorInfo;
                }
            }
            return $this->redirect('/member/ecashWithdrawal');
        }
    }

    public function executeBdetails()
    {
        $this->bonus = $this->getRequestParameter('bonus');

        $c = new Criteria();
        $c->add(TblMemberCommPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $c->addAnd(TblMemberCommPeer::F_TYPE, $this->getRequestParameter('bonus'));

        $this->TblBonus = TblMemberCommPeer::doSelect($c);
    }

    public function executeBonusDetails()
    {
        $dsb = $this->getCommissionBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::COMMISSION_TYPE_DSB);
        $gdb = $this->getCommissionBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::COMMISSION_TYPE_GDB);
        $this->dsb = number_format($dsb, 2);
        $this->gdb = number_format($gdb, 2);
        $this->total = number_format($dsb + $gdb, 2);
    }

    public function executeSalesDetails()
    {
        $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($distDB);
        $joinDate = $distDB->getActiveDatetime();
        $joinMonth = date('m', strtotime($joinDate));
        $currentMonth = date('m');

        $anode = array();

        $idx = 0;
        for ($i = intval($joinMonth); $i <= intval($currentMonth); $i++) {
            $anode[$idx]["month"] = $i;
            $anode[$idx]["left_month_sales"] = $this->getMonthSales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, $i, date('Y'));
            $anode[$idx]["right_month_sales"] = $this->getMonthSales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, $i, date('Y'));
            $idx++;
        }
        $this->anode = $anode;
    }

    /* ************************************************************************************************************************************************************************************************************************************************************************
   *************************************************************************************************************************************************************************************************************************************************************************
   *************************************************************************************************************************************************************************************************************************************************************************
   *************************************************************************************************************************************************************************************************************************************************************************
   *************************************************************************************************************************************************************************************************************************************************************************
   *************************************************************************************************************************************************************************************************************************************************************************
   *************************************************************************************************************************************************************************************************************************************************************************
   *************************************************************************************************************************************************************************************************************************************************************************
   * */

    public function executeProfile()
    {
    }

    public function executeRegistration()
    {
    }

    public function executeVerifyNickName()
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::NICKNAME, $this->getRequestParameter('nickName'));
        $exist = MlmDistributorPeer::doSelectOne($c);

        if ($exist) {
            echo 'false';
        } else {
            echo 'true';
        }

        return sfView::HEADER_ONLY;
    }

    public function executeViewProfile()
    {
        $char = strtoupper(substr(str_shuffle('abcdefghjkmnpqrstuvwxyz'), 0, 2));
        // Concatenate the random string onto the random numbers
        // The font 'Anorexia' doesn't have a character for '8', so the numbers will only go up to 7
        // '0' is left out to avoid confusion with 'O'

        $str = rand(1, 7) . rand(1, 7) . $char;
        $this->getUser()->setAttribute(Globals::SYSTEM_CAPTCHA_ID, $str);

        $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($distDB);

        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, $distDB->getParentId());
        $sponsor = MlmDistributorPeer::doSelectOne($c);
        if (!$sponsor) {
            $sponsor = new MlmDistributor();
        }

        $this->sponsor = $sponsor;
        $this->distDB = $distDB;
    }

    public function executeDailyBonus()
    {
        print_r("Start<br>");
        $test_schedular = new TestSchedular();
        $test_schedular->setAccessIp($this->getRequest()->getHttpHeader('addr','remote'));
        $test_schedular->save();

        $c = new Criteria();
        $c->add(MlmDailyBonusLogPeer::BONUS_TYPE, Globals::DAILY_BONUS_LOG_TYPE_DAILY);
        $c->addDescendingOrderByColumn(MlmDailyBonusLogPeer::BONUS_DATE);
        $mlmDistPairingDBs = MlmDailyBonusLogPeer::doSelectOne($c);
        print_r("Fetch Daily Bonus Log<br>");
        //print_r(date("Y/m/d h:i:s A")."<br>");

        $dateUtil = new DateUtil();
        $currentDate = $dateUtil->formatDate("Y-m-d", date("Y-m-d"));
        print_r("currentDate=".$currentDate."<br>");

        if ($mlmDistPairingDBs) {
            $bonusDate = $dateUtil->formatDate("Y-m-d", $mlmDistPairingDBs->getBonusDate());
            print_r("bonusDate=".$bonusDate."<br>");

            $level = 0;
            while ($level < 100) {
                print_r("level start ".$level."<br><br>");
                if ($bonusDate == $currentDate) {
                    print_r("break<br>");
                    break;
                }

                $c = new Criteria();
                //$c->add(MlmDistPairingPeer::DIST_ID, 476);
                $mlmDistPairingDBs = MlmDistPairingPeer::doSelect($c);
                foreach ($mlmDistPairingDBs as $mlmDistPairingDB) {
                    $distId = $mlmDistPairingDB->getDistId();
                    //$flushLimit = $mlmDistPairingDB->getFlushLimit() - $this->getDsbAmount($distId, $bonusDate);
                    $flushLimit = $mlmDistPairingDB->getFlushLimit();
                    print_r("DistId ".$distId."<br>");

                    if ($mlmDistPairingDB->getLeftBalance() > 0 && $mlmDistPairingDB->getRightBalance() > 0) {
                        print_r("Start Calculate bonus:".$bonusDate."<br>");
                        // requery for paring ledger
                        $leftBalance = $this->findPairingLedgers($distId, Globals::PLACEMENT_LEFT, $bonusDate);
                        $rightBalance = $this->findPairingLedgers($distId, Globals::PLACEMENT_RIGHT, $bonusDate);
                        $minBalance = $leftBalance;
                        if ($rightBalance < $leftBalance) {
                            $minBalance = $rightBalance;
                        }
                        print_r("leftBalance ".$leftBalance."<br>");
                        print_r("rightBalance ".$rightBalance."<br>");
                        print_r("minBalance ".$minBalance."<br>");
                        if ($leftBalance > 0 && $rightBalance > 0) {
                            $this->updateDistPairingLeader($distId, Globals::PLACEMENT_LEFT, $minBalance);
                            $this->updateDistPairingLeader($distId, Globals::PLACEMENT_RIGHT, $minBalance);

                            // start paring bonus
                            $distributorDB = MlmDistributorPeer::retrieveByPK($distId);
                            $packageDB = MlmPackagePeer::retrieveByPK($distributorDB->getRankId());

                            $pairingPercentage = $packageDB->getPairingBonus();
                            $pairingBonusAmount = $minBalance * $pairingPercentage / 100;
                            print_r("pairingBonusAmount =".$pairingBonusAmount."<br>");
                            $flushAmount = 0;
                            if ($pairingBonusAmount > $flushLimit) {
                                $flushAmount = $pairingBonusAmount - $flushLimit;
                            }

                            /******************************/
                            /*  Commission
                            /******************************/
                            $c = new Criteria();
                            $c->add(MlmDistCommissionPeer::DIST_ID, $distId);
                            $c->add(MlmDistCommissionPeer::COMMISSION_TYPE, Globals::COMMISSION_TYPE_GDB);
                            $sponsorDistCommissionDB = MlmDistCommissionPeer::doSelectOne($c);

                            $commissionBalance = 0;
                            if (!$sponsorDistCommissionDB) {
                                $sponsorDistCommissionDB = new MlmDistCommission();
                                $sponsorDistCommissionDB->setDistId($distId);
                                $sponsorDistCommissionDB->setCommissionType(Globals::COMMISSION_TYPE_GDB);
                                $sponsorDistCommissionDB->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            } else {
                                $commissionBalance = $sponsorDistCommissionDB->getBalance();
                            }
                            $sponsorDistCommissionDB->setBalance($commissionBalance + $pairingBonusAmount);
                            $sponsorDistCommissionDB->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $sponsorDistCommissionDB->save();

                            $c = new Criteria();
                            $c->add(MlmDistCommissionLedgerPeer::DIST_ID, $distId);
                            $c->add(MlmDistCommissionLedgerPeer::COMMISSION_TYPE, Globals::COMMISSION_TYPE_GDB);
                            $c->addDescendingOrderByColumn(MlmDistCommissionLedgerPeer::CREATED_ON);
                            $sponsorDistCommissionLedgerDB = MlmDistCommissionLedgerPeer::doSelectOne($c);

                            $gdbBalance = 0;
                            if ($sponsorDistCommissionLedgerDB)
                                $gdbBalance = $sponsorDistCommissionLedgerDB->getBalance();

                            /******************************/
                            /*  Account
                            /******************************/
                            $c = new Criteria();
                            $c->add(MlmAccountLedgerPeer::DIST_ID, $distId);
                            $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
                            $c->addDescendingOrderByColumn(MlmAccountLedgerPeer::CREATED_ON);
                            $accountLedgerDB = MlmAccountLedgerPeer::doSelectOne($c);
                            $this->forward404Unless($accountLedgerDB);
                            $distAccountEcashBalance = $accountLedgerDB->getBalance();

                            // pairing amount
                            $ecashBalance = $distAccountEcashBalance + $pairingBonusAmount;
                            $mlm_account_ledger = new MlmAccountLedger();
                            $mlm_account_ledger->setDistId($distId);
                            $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                            $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_GDB);
                            $mlm_account_ledger->setRemark("GROUP PAIRING BONUS AMOUNT (" . $bonusDate . ")");
                            $mlm_account_ledger->setCredit($pairingBonusAmount);
                            $mlm_account_ledger->setDebit(0);
                            $mlm_account_ledger->setBalance($ecashBalance);
                            $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $mlm_account_ledger->save();

                            //commission
                            $commissionBalance = $gdbBalance + $pairingBonusAmount;
                            $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                            $sponsorDistCommissionledger->setDistId($distId);
                            $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_GDB);
                            $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_PAIRED);
                            $sponsorDistCommissionledger->setCredit($pairingBonusAmount);
                            $sponsorDistCommissionledger->setDebit(0);
                            $sponsorDistCommissionledger->setBalance($commissionBalance);
                            $sponsorDistCommissionledger->setRemark("GROUP PAIRING AMOUNT (" . $bonusDate . ")");
                            $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $sponsorDistCommissionledger->save();

                            // flush amount
                            if ($flushAmount != 0) {
                                $ecashBalance = $ecashBalance - $flushAmount;
                                $mlm_account_ledger = new MlmAccountLedger();
                                $mlm_account_ledger->setDistId($distId);
                                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_GDB);
                                $mlm_account_ledger->setRemark("FLUSH " . $pairingBonusAmount . " (" . $bonusDate . ")");
                                $mlm_account_ledger->setCredit(0);
                                $mlm_account_ledger->setDebit($flushAmount);
                                $mlm_account_ledger->setBalance($ecashBalance);
                                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $mlm_account_ledger->save();

                                $commissionBalance = $commissionBalance - $flushAmount;
                                $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                                $sponsorDistCommissionledger->setDistId($distId);
                                $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_GDB);
                                $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_PAIRED);
                                $sponsorDistCommissionledger->setCredit(0);
                                $sponsorDistCommissionledger->setDebit($flushAmount);
                                $sponsorDistCommissionledger->setBalance($commissionBalance);
                                $sponsorDistCommissionledger->setRemark("FLUSH " . $pairingBonusAmount . " (" . $bonusDate . ")");
                                $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $sponsorDistCommissionledger->save();

                                $pairingBonusAmount = $flushAmount;
                            }
                            $maintenanceBalance = $pairingBonusAmount * Globals::BONUS_MAINTENANCE_PERCENTAGE;
                            $ecashBalance = $ecashBalance - $maintenanceBalance;
                            $maintenanceEcashAccountLedger = new MlmAccountLedger();
                            $maintenanceEcashAccountLedger->setDistId($distId);
                            $maintenanceEcashAccountLedger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                            $maintenanceEcashAccountLedger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_MAINTENANCE);
                            $maintenanceEcashAccountLedger->setRemark("MAINTENANCE BALANCE (" . $bonusDate . ")");
                            $maintenanceEcashAccountLedger->setCredit(0);
                            $maintenanceEcashAccountLedger->setDebit($maintenanceBalance);
                            $maintenanceEcashAccountLedger->setBalance($ecashBalance);
                            $maintenanceEcashAccountLedger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $maintenanceEcashAccountLedger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $maintenanceEcashAccountLedger->save();

                            $this->revalidateAccount($distId, Globals::ACCOUNT_TYPE_ECASH);

                            $commissionBalance = $commissionBalance - $maintenanceBalance;
                            $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                            $sponsorDistCommissionledger->setDistId($distId);
                            $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_GDB);
                            $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_PAIRED);
                            $sponsorDistCommissionledger->setCredit(0);
                            $sponsorDistCommissionledger->setDebit($maintenanceBalance);
                            $sponsorDistCommissionledger->setBalance($commissionBalance);
                            $sponsorDistCommissionledger->setRemark("MAINTENANCE BALANCE (" . $bonusDate . ")");
                            $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $sponsorDistCommissionledger->save();

                            $this->revalidateCommission($distId, Globals::COMMISSION_TYPE_GDB);
                            /******************************/
                            /*  Maintenance
                            /******************************/
                            $c = new Criteria();
                            $c->add(MlmAccountLedgerPeer::DIST_ID, $distId);
                            $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_MAINTENANCE);
                            $c->addDescendingOrderByColumn(MlmAccountLedgerPeer::CREATED_ON);
                            $accountLedgerDB = MlmAccountLedgerPeer::doSelectOne($c);
                            $this->forward404Unless($accountLedgerDB);
                            $distAccountMaintenanceBalance = $accountLedgerDB->getBalance();

                            $maintenanceAccountLedger = new MlmAccountLedger();
                            $maintenanceAccountLedger->setDistId($distId);
                            $maintenanceAccountLedger->setAccountType(Globals::ACCOUNT_TYPE_MAINTENANCE);
                            $maintenanceAccountLedger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_GDB);
                            $maintenanceAccountLedger->setRemark("PAIRING BALANCE " . number_format($pairingBonusAmount, 2) . " (" . $bonusDate . ")");
                            $maintenanceAccountLedger->setCredit($maintenanceBalance);
                            $maintenanceAccountLedger->setDebit(0);
                            $maintenanceAccountLedger->setBalance($distAccountMaintenanceBalance + $maintenanceBalance);
                            $maintenanceAccountLedger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $maintenanceAccountLedger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                            $maintenanceAccountLedger->save();

                            $this->revalidateAccount($distId, Globals::ACCOUNT_TYPE_MAINTENANCE);
                        }
                    }
                }

                $bonusDate = $dateUtil->formatDate("Y-m-d", $dateUtil->addDate($bonusDate, 1, 0, 0));
                $mlm_daily_bonus_log = new MlmDailyBonusLog();
                $mlm_daily_bonus_log->setAccessIp($this->getRequest()->getHttpHeader('addr','remote'));
                $mlm_daily_bonus_log->setBonusType(Globals::DAILY_BONUS_LOG_TYPE_DAILY);
                $mlm_daily_bonus_log->setBonusDate($bonusDate);
                $mlm_daily_bonus_log->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_daily_bonus_log->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_daily_bonus_log->save();
                $level++;
            }
        }
        print_r("+++++ Verify +++++ share volume amount");
        $eShareTradingService = new EShareTradingService();
        $eShareTradingService->verifyShareAmount();
        print_r("Done");
        return sfView::HEADER_ONLY;
    }

    /************************************************************************************************************************
     * function
     ************************************************************************************************************************/
    function generateFcode($country = 'China (PRC)')
    {
        if ($country == 'Malaysia') {
            $max_digit = 999999;
            $digit = 6;
        } elseif ($country == 'Indonesia') {
            $max_digit = 9999999;
            $digit = 7;
        } elseif ($country == 'China (PRC)' || $country == 'China') {
            $max_digit = 99999999;
            $digit = 8;
        } else {
            $max_digit = 999999999;
            $digit = 9;
        }

        while (true) {
            $fcode = rand(0, $max_digit) . "";
            $fcode = str_pad($fcode, $digit, "0", STR_PAD_LEFT);
            /*
            for ($x=0; $x < ($digit - strlen($fcode)); $x++) {
                $fcode = "0".$fcode;
            }
			*/
            $c = new Criteria();
            $c->add(AppUserPeer::USERNAME, $fcode);
            $existUser = AppUserPeer::doSelectOne($c);

            if (!$existUser) {
                break;
            }
        }
        return $fcode;
    }

    function generateFPin()
    {
        while (true) {
            $fpin = rand(0, 999999999999) . "";
            for ($x = 0; $x < (12 - strlen($fpin)); $x++) {
                $fpin = "1" . $fpin;
            }

            $c = new Criteria();
            $c->add(TblPinPeer::F_PIN, $fpin);
            $existPin = TblPinPeer::doSelectOne($c);

            if (!$existPin) {
                break;
            }
        }

        return $fpin;
    }

    function getParentId($sponsorId)
    {
        $userId = 0;

        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $existUser = MlmDistributorPeer::doSelectOne($c);

        if ($existUser) {
            $userId = $existUser->getDistributorId();
        }

        return $userId;
    }

    function getTradingPower()
    {
        $tradingPower = 0;

        $c = new Criteria();
        $c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_TRADING_POWER);
        $exist = TblSettingPeer::doSelectOne($c);

        if ($exist) {
            $tradingPower = $exist->getFValue();
        }

        return $tradingPower;
    }

    function revalidateAccount($distributorId, $accountType)
    {
        $balance = $this->getAccountBalance($distributorId, $accountType);

        $c = new Criteria();
        $c->add(MlmAccountPeer::ACCOUNT_TYPE, $accountType);
        $c->add(MlmAccountPeer::DIST_ID, $distributorId);
        $tbl_account = MlmAccountPeer::doSelectOne($c);

        if (!$tbl_account) {
            $tbl_account = new MlmAccount();
            $tbl_account->setDistId($distributorId);
            $tbl_account->setAccountType($accountType);
        }

        $tbl_account->setBalance($balance);
        $tbl_account->save();
    }

    function revalidateCommission($distributorId, $commissionType)
    {
        $balance = $this->getCommissionBalance($distributorId, $commissionType);

        $c = new Criteria();
        $c->add(MlmDistCommissionPeer::COMMISSION_TYPE, $commissionType);
        $c->add(MlmDistCommissionPeer::DIST_ID, $distributorId);
        $tbl_account = MlmDistCommissionPeer::doSelectOne($c);

        if (!$tbl_account) {
            $tbl_account = new MlmDistCommission();
            $tbl_account->setDistId($distributorId);
            $tbl_account->setCommissionType($commissionType);
        }

        $tbl_account->setBalance($balance);
        $tbl_account->save();
    }

    function getCommissionBalance($distributorId, $commissionType)
    {
        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_commission_ledger WHERE dist_id = " . $distributorId . " AND commission_type = '" . $commissionType . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function revalidatePairing($distributorId, $leftRight)
    {
        $balance = $this->getPairingBalance($distributorId, $leftRight);

        $c = new Criteria();
        $c->add(MlmDistPairingPeer::DIST_ID, $distributorId);
        $tbl_account = MlmDistPairingPeer::doSelectOne($c);

        if (!$tbl_account) {
            $tbl_account = new MlmDistPairing();
            $tbl_account->setDistId($distributorId);
            $tbl_account->setLeftBalance(0);
            $tbl_account->setRightBalance(0);
        }
        if (Globals::PLACEMENT_LEFT == $leftRight) {
            $tbl_account->setLeftBalance($balance);
        } else if (Globals::PLACEMENT_RIGHT == $leftRight) {
            $tbl_account->setRightBalance($balance);
        }

        $tbl_account->save();
    }

    function getPairingBalance($distributorId, $leftRight)
    {
        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId . " AND left_right = '" . $leftRight . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        $count = 0;
        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getAccountBalance($distributorId, $accountType)
    {
        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_account_ledger WHERE dist_id = " . $distributorId . " AND account_type = '" . $accountType . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function format2decimal($d)
    {
        return ceil($d * 100) / 100;
    }

    function checkHasChild($distId)
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::PARENT_ID, $distId);
        $c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $list = MlmDistributorPeer::doSelect($c);
        if ($list) {
            return true;
        }
        return false;
    }

    function doActivateAccount($distId, $sponsorId, $packageId, $paymentType)
    {
        // $distId = parentId (sponsorId)
        // $sponsorId = been sponsored by $distId
        $packageDB = MlmPackagePeer::retrieveByPK($packageId);
        $this->forward404Unless($packageDB);
        $packageAmount = $packageDB->getPrice();

        /* ****************************************************
         * get distributor last account ledger epoint balance
         * ***************************************************/
        $c = new Criteria();
        $c->add(MlmAccountLedgerPeer::DIST_ID, $distId);
        if ("epoint" == $paymentType) {
            $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_EPOINT);
        } else if ("ecash" == $paymentType) {
            $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
        }
        $c->addDescendingOrderByColumn(MlmAccountLedgerPeer::CREATED_ON);
        $accountLedgerDB = MlmAccountLedgerPeer::doSelectOne($c);
        $this->forward404Unless($accountLedgerDB);

        $sponsorAccountBalance = $accountLedgerDB->getBalance();

        /* ****************************************************
         * get sponsored distributor and user
         * ***************************************************/
        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, $sponsorId);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_PENDING);
        $sponsoredDistDB = MlmDistributorPeer::doSelectOne($c);
        $this->forward404Unless($sponsoredDistDB);

        $userDB = AppUserPeer::retrieveByPK($sponsoredDistDB->getUserId());
        $this->forward404Unless($userDB);

        /* ****************************************************
         * update sponsored distributor and user
         * ***************************************************/
        $sponsoredDistDB->setRankId($packageDB->getPackageId());
        $sponsoredDistDB->setRankCode($packageDB->getPackageName());
        $sponsoredDistDB->setStatusCode(Globals::STATUS_ACTIVE);
        $sponsoredDistDB->setActiveDatetime(date("Y/m/d h:i:s A"));
        $sponsoredDistDB->save();

        $userDB->setStatusCode(Globals::STATUS_ACTIVE);
        $userDB->save();

        /* ****************************************************
         * Start Calculation
         * ***************************************************/
        /*$c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_CPS);
        $settingDB = AppSettingPeer::doSelectOne($c);*/
        //$eshare = ($packageDB->getPrice() / $settingDB->getSettingValue()) * $packageDB->getShareRatio() / 100;
        $eshare = 0;
        $ecash = $packageDB->getPrice() * $packageDB->getShareRatio() / 100;

        $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_ECASH, $ecash, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
        $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_EPOINT, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
        $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_ESHARE, $eshare, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
        $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_MAINTENANCE, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");

        /* ****************************************************
         * Update distributor account
         * ***************************************************/
        $mlm_account_ledger = new MlmAccountLedger();
        $mlm_account_ledger->setDistId($distId);
        if ("epoint" == $paymentType) {
            $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
        } else if ("ecash" == $paymentType) {
            $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
        }
        $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);
        $mlm_account_ledger->setRemark("DIRECT SPONSOR TO " . $sponsoredDistDB->getDistributorCode());
        $mlm_account_ledger->setCredit(0);
        $mlm_account_ledger->setDebit($packageDB->getPrice());
        $mlm_account_ledger->setBalance($sponsorAccountBalance - $packageDB->getPrice());
        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->save();

        if ("epoint" == $paymentType) {
            $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        } else if ("ecash" == $paymentType) {
            $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        }

        /******************************/
        /*  Direct Sponsor Bonus
        /******************************/
        $sponsorDist = MlmDistributorPeer::retrieveByPK($distId);
        $sponsorPackage = MlmPackagePeer::retrieveByPK($sponsorDist->getRankId());

        $directSponsorPercentage = $sponsorPackage->getDirectSponsor();
        $directSponsorBonusAmount = $directSponsorPercentage * $packageAmount / 100;
        $maintenanceBalance = $directSponsorBonusAmount * Globals::BONUS_MAINTENANCE_PERCENTAGE;
        //$directSponsorBonusAmount = $directSponsorBonusAmount - $maintenanceBalance;

        $c = new Criteria();
        $c->add(MlmAccountLedgerPeer::DIST_ID, $distId);
        $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
        $c->addDescendingOrderByColumn(MlmAccountLedgerPeer::CREATED_ON);
        $accountLedgerDB = MlmAccountLedgerPeer::doSelectOne($c);
        $this->forward404Unless($accountLedgerDB);
        $distAccountEcashBalance = $accountLedgerDB->getBalance();

        $mlm_account_ledger = new MlmAccountLedger();
        $mlm_account_ledger->setDistId($distId);
        $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
        $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_DSB);
        $mlm_account_ledger->setRemark("DIRECT SPONSOR BONUS AMOUNT (" . $sponsoredDistDB->getDistributorCode() . ")");
        $mlm_account_ledger->setCredit($directSponsorBonusAmount);
        $mlm_account_ledger->setDebit(0);
        $mlm_account_ledger->setBalance($distAccountEcashBalance + $directSponsorBonusAmount);
        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->save();

        $maintenanceEcashAccountLedger = new MlmAccountLedger();
        $maintenanceEcashAccountLedger->setDistId($distId);
        $maintenanceEcashAccountLedger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
        $maintenanceEcashAccountLedger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_MAINTENANCE);
        $maintenanceEcashAccountLedger->setRemark("MAINTENANCE BALANCE (" . $sponsoredDistDB->getDistributorCode() . ")");
        $maintenanceEcashAccountLedger->setCredit(0);
        $maintenanceEcashAccountLedger->setDebit($maintenanceBalance);
        $maintenanceEcashAccountLedger->setBalance($distAccountEcashBalance + $directSponsorBonusAmount - $maintenanceBalance);
        $maintenanceEcashAccountLedger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $maintenanceEcashAccountLedger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $maintenanceEcashAccountLedger->save();

        $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);

        /******************************/
        /*  Maintenance
        /******************************/
        $c = new Criteria();
        $c->add(MlmAccountLedgerPeer::DIST_ID, $distId);
        $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_MAINTENANCE);
        $c->addDescendingOrderByColumn(MlmAccountLedgerPeer::CREATED_ON);
        $accountLedgerDB = MlmAccountLedgerPeer::doSelectOne($c);
        $this->forward404Unless($accountLedgerDB);
        $distAccountMaintenanceBalance = $accountLedgerDB->getBalance();

        $maintenanceAccountLedger = new MlmAccountLedger();
        $maintenanceAccountLedger->setDistId($distId);
        $maintenanceAccountLedger->setAccountType(Globals::ACCOUNT_TYPE_MAINTENANCE);
        $maintenanceAccountLedger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_DSB);
        $maintenanceAccountLedger->setRemark("MAINTENANCE BALANCE (" . $sponsoredDistDB->getDistributorCode() . ")");
        $maintenanceAccountLedger->setCredit($maintenanceBalance);
        $maintenanceAccountLedger->setDebit(0);
        $maintenanceAccountLedger->setBalance($distAccountMaintenanceBalance + $maintenanceBalance);
        $maintenanceAccountLedger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $maintenanceAccountLedger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $maintenanceAccountLedger->save();

        $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_MAINTENANCE);

        /******************************/
        /*  Commission
        /******************************/
        $c = new Criteria();
        $c->add(MlmDistCommissionPeer::DIST_ID, $distId);
        $c->add(MlmDistCommissionPeer::COMMISSION_TYPE, Globals::COMMISSION_TYPE_DSB);
        $sponsorDistCommissionDB = MlmDistCommissionPeer::doSelectOne($c);

        $commissionBalance = 0;
        if (!$sponsorDistCommissionDB) {
            $sponsorDistCommissionDB = new MlmDistCommission();
            $sponsorDistCommissionDB->setDistId($distId);
            $sponsorDistCommissionDB->setCommissionType(Globals::COMMISSION_TYPE_DSB);
            $sponsorDistCommissionDB->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        } else {
            $commissionBalance = $sponsorDistCommissionDB->getBalance();
        }
        $sponsorDistCommissionDB->setBalance($commissionBalance + $directSponsorBonusAmount);
        $sponsorDistCommissionDB->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $sponsorDistCommissionDB->save();

        $c = new Criteria();
        $c->add(MlmDistCommissionLedgerPeer::DIST_ID, $distId);
        $c->add(MlmDistCommissionLedgerPeer::COMMISSION_TYPE, Globals::COMMISSION_TYPE_DSB);
        $c->addDescendingOrderByColumn(MlmDistCommissionLedgerPeer::CREATED_ON);
        $sponsorDistCommissionLedgerDB = MlmDistCommissionLedgerPeer::doSelectOne($c);

        $dsbBalance = 0;
        if ($sponsorDistCommissionLedgerDB)
            $dsbBalance = $sponsorDistCommissionLedgerDB->getBalance();

        $sponsorDistCommissionledger = new MlmDistCommissionLedger();
        $sponsorDistCommissionledger->setDistId($distId);
        $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_DSB);
        $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_REGISTER);
        $sponsorDistCommissionledger->setCredit($directSponsorBonusAmount);
        $sponsorDistCommissionledger->setDebit(0);
        $sponsorDistCommissionledger->setBalance($dsbBalance + $directSponsorBonusAmount);
        $sponsorDistCommissionledger->setRemark("DIRECT SPONSOR BONUS AMOUNT (" . $sponsoredDistDB->getDistributorCode() . ")");
        $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $sponsorDistCommissionledger->save();

        $sponsorDistCommissionledger = new MlmDistCommissionLedger();
        $sponsorDistCommissionledger->setDistId($distId);
        $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_DSB);
        $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_REGISTER);
        $sponsorDistCommissionledger->setCredit(0);
        $sponsorDistCommissionledger->setDebit($maintenanceBalance);
        $sponsorDistCommissionledger->setBalance($dsbBalance + $directSponsorBonusAmount - $maintenanceBalance);
        $sponsorDistCommissionledger->setRemark("MAINTENANCE BALANCE (" . $sponsoredDistDB->getDistributorCode() . ")");
        $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $sponsorDistCommissionledger->save();

        $this->revalidateCommission($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::COMMISSION_TYPE_DSB);

        /****************************/
        /*****  Send email **********/
        /****************************/
        error_reporting(E_STRICT);

        date_default_timezone_set(date_default_timezone_get());

        include_once('class.phpmailer.php');

        $subject = $this->getContext()->getI18N()->__("Tune International Group account activation notification", null, 'email');
        $body = $this->getContext()->getI18N()->__("Dear %1%", array('%1%' => $sponsoredDistDB->getNickname()), 'email') . ",<p><p>
        <p>" . $this->getContext()->getI18N()->__("Your account has been activated", null, 'email') . "</p>
        <p><b>" . $this->getContext()->getI18N()->__("Shareholder ID", null) . ": " . $sponsoredDistDB->getDistributorCode() . "</b>
        <p><b>" . $this->getContext()->getI18N()->__("Package Rank", null) . ": " . $sponsoredDistDB->getRankCode() . "</b>
        <p><b>" . $this->getContext()->getI18N()->__("Package Price", null) . ": " . $packageDB->getPrice() . "</b>";

        $mail = new PHPMailer();
        $mail->IsMail(); // telling the class to use SMTP
        $mail->Host = Globals::EMAIL_HOST; // SMTP server
        $mail->Sender = Globals::EMAIL_FROM_NOREPLY;
        $mail->From = Globals::EMAIL_FROM_NOREPLY;
        $mail->FromName = Globals::EMAIL_FROM_NOREPLY_NAME;
        $mail->Subject = $subject;
        $mail->CharSet="utf-8";
        $text_body = $body;

        $mail->Body = $body;
        $mail->AltBody = $text_body;
        $mail->AddAddress($sponsoredDistDB->getEmail(), $sponsoredDistDB->getNickname());
        $mail->AddBCC("r9projecthost@gmail.com", "r9projecthost");

        if (!$mail->Send()) {
            //echo $mail->ErrorInfo;
        }
    }

    function doActivateAccountByEcash($distId, $sponsorId, $packageId)
    {
        // $distId = parentId (sponsorId)
        // $sponsorId = been sponsored by $distId
        $packageDB = MlmPackagePeer::retrieveByPK($packageId);
        $this->forward404Unless($packageDB);

        /* ****************************************************
         * get distributor last account ledger ecash balance
         * ***************************************************/
        $c = new Criteria();
        $c->add(MlmAccountLedgerPeer::DIST_ID, $distId);
        $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
        $c->addDescendingOrderByColumn(MlmAccountLedgerPeer::CREATED_ON);
        $accountLedgerDB = MlmAccountLedgerPeer::doSelectOne($c);
        $this->forward404Unless($accountLedgerDB);

        $distAccountECashBalance = $accountLedgerDB->getBalance();

        /* ****************************************************
         * get sponsored distributor and user
         * ***************************************************/
        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, $sponsorId);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_PENDING);
        $distDB = MlmDistributorPeer::doSelectOne($c);
        $this->forward404Unless($distDB);

        $userDB = AppUserPeer::retrieveByPK($distDB->getUserId());
        $this->forward404Unless($userDB);

        /* ****************************************************
         * update sponsored distributor and user
         * ***************************************************/
        $distDB->setRankId($packageDB->getPackageId());
        $distDB->setRankCode($packageDB->getPackageName());
        $distDB->setStatusCode(Globals::STATUS_ACTIVE);
        $distDB->setActiveDatetime(date("Y/m/d h:i:s A"));
        $distDB->save();

        $userDB->setStatusCode(Globals::STATUS_ACTIVE);
        $userDB->save();

        /* ****************************************************
         * Start Calculation
         * ***************************************************/
        /*$c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_CPS);
        $settingDB = AppSettingPeer::doSelectOne($c);*/
        //$eshare = ($packageDB->getPrice() / $settingDB->getSettingValue()) * $packageDB->getShareRatio() / 100;
        $eshare = 0;
        $ecash = $packageDB->getPrice() * $packageDB->getShareRatio();

        $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_ECASH, $ecash, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
        $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_EPOINT, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
        $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_ESHARE, $eshare, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
        $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_MAINTENANCE, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");

        /* ****************************************************
         * Update distributor account
         * ***************************************************/
        $mlm_account_ledger = new MlmAccountLedger();
        $mlm_account_ledger->setDistId($distId);
        $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
        $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);
        $mlm_account_ledger->setRemark("DIRECT SPONSOR TO " . $distDB->getDistributorCode());
        $mlm_account_ledger->setCredit(0);
        $mlm_account_ledger->setDebit($packageDB->getPrice());
        $mlm_account_ledger->setBalance($distAccountECashBalance - $packageDB->getPrice());
        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->save();

        $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);

        /******************************/
        /*  Direct Sponsor Bonus
        /******************************/
    }

    function doSaveAccount($distId, $accountType, $credit, $debit, $transactionType, $remarks)
    {
        $c = new Criteria();
        $c->add(MlmAccountPeer::ACCOUNT_TYPE, $accountType);
        $c->add(MlmAccountPeer::DIST_ID, $distId);
        $mlm_account = MlmAccountPeer::doSelectOne($c);

        if (!$mlm_account) {
            $mlm_account = new MlmAccount();
        }
        $mlm_account->setDistId($distId);
        $mlm_account->setAccountType($accountType);
        $mlm_account->setBalance($credit - $debit);
        $mlm_account->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account->save();

        $mlm_account_ledger = new MlmAccountLedger();
        $mlm_account_ledger->setDistId($distId);
        $mlm_account_ledger->setAccountType($accountType);
        $mlm_account_ledger->setTransactionType($transactionType);
        $mlm_account_ledger->setRemark($remarks);
        $mlm_account_ledger->setCredit($credit);
        $mlm_account_ledger->setDebit($debit);
        $mlm_account_ledger->setBalance($credit - $debit);
        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->save();
    }

    function getDistributorInformation($distCode)
    {
        $c = new Criteria();

        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $distCode);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $distDB = MlmDistributorPeer::doSelectOne($c);
        $this->forward404Unless($distDB);

        return $distDB;
    }

    function getPlacementDistributorInformation($uplineDistId, $placeLocation)
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $uplineDistId);
        $c->add(MlmDistributorPeer::PLACEMENT_POSITION, $placeLocation);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);

        $placeDB = MlmDistributorPeer::doSelectOne($c);
        return $placeDB;
    }

    function getTotalPosition($distCode, $position)
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::PLACEMENT_POSITION, $position);
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $distCode, Criteria::NOT_EQUAL);
        $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%|" . $distCode . "|%", Criteria::LIKE);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);

        $totalDis = MlmDistributorPeer::doCount($c);
        return $totalDis;
    }

    function queryDistPairing($distributorId)
    {
        $c = new Criteria();
        $c->add(MlmDistPairingPeer::DIST_ID, $distributorId);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $mlmDist = MlmDistPairingPeer::doSelectOne($c);
        if (!$mlmDist) {
            $distDB = MlmDistributorPeer::retrieveByPK($distributorId);
            $distPairingDB = new MlmDistPairing();
            $distPairingDB->setDistId($distributorId);

            $packageDB = MlmPackagePeer::retrieveByPK($distDB->getRankId());
            $this->forward404Unless($packageDB);

            $distPairingDB->setLeftBalance(0);
            $distPairingDB->setRightBalance(0);
            $distPairingDB->setFlushLimit($packageDB->getDailyMaxPairing());
            $distPairingDB->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $distPairingDB->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $distPairingDB->save();
            return $distPairingDB;
        }
        return $mlmDist;
    }

    function getThisMonthSales($distributorId, $position)
    {
        $dateUtil = new DateUtil();

        $d = $dateUtil->getMonth();
        $firstOfMonth = date('Y-m-j', $d["first_of_month"]) . " 00:00:00";
        $lastOfMonth = date('Y-m-j', $d["last_of_month"]) . " 23:59:59";

        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId
                 . " AND left_right = '" . $position . "'"
                 . " AND transaction_type = '" . Globals::PAIRING_LEDGER_REGISTER . "'"
                 . " AND created_on >= '" . $firstOfMonth . "' AND created_on <= '" . $lastOfMonth . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        //var_dump($query);
        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getMonthSales($distributorId, $position, $month, $year)
    {
        $dateUtil = new DateUtil();

        $d = $dateUtil->getMonth($month, $year);
        $firstOfMonth = date('Y-m-j', $d["first_of_month"]) . " 00:00:00";
        $lastOfMonth = date('Y-m-j', $d["last_of_month"]) . " 23:59:59";

        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId
                 . " AND left_right = '" . $position . "'"
                 . " AND transaction_type = '" . Globals::PAIRING_LEDGER_REGISTER . "'"
                 . " AND created_on >= '" . $firstOfMonth . "' AND created_on <= '" . $lastOfMonth . "'";
        //var_dump($query);
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function findDailyWithdrawal($distributorId, $date)
    {
        $query = "SELECT SUM(deduct) AS SUB_TOTAL FROM mlm_ecash_withdraw WHERE dist_id = " . $distributorId;

        if ($date != null) {
            $query .= " AND created_on >= '" . $date . " 00:00:00' AND created_on <= '" . $date . " 23:59:59'";
        }
        //var_dump($query);
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function findPairingLedgers($distributorId, $position, $date)
    {
        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId
                 . " AND left_right = '" . $position . "'";

        if ($date != null) {
            $query .= " AND created_on <= '" . $date . " 23:59:59'";
        }
        //var_dump($query);
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getDsbAmount($distributorId, $date)
    {
        $query = "SELECT SUM(credit) AS SUB_TOTAL FROM mlm_dist_commission_ledger WHERE dist_id = " . $distributorId
                 . " AND commission_type = '" . Globals::ACCOUNT_LEDGER_ACTION_DSB . "'";

        $query .= " AND created_on >= '" . $date . " 00:00:00'";
        $query .= " AND created_on <= '" . $date . " 23:59:59'";

        //var_dump($query);
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function updateDistPairingLeader($distId, $position, $debit, $remark="PAIRED", $transactionType=Globals::PAIRING_LEDGER_PAIRED)
    {
        $c = new Criteria();
        $c->add(MlmDistPairingLedgerPeer::DIST_ID, $distId);
        $c->add(MlmDistPairingLedgerPeer::LEFT_RIGHT, $position);
        $c->addDescendingOrderByColumn(MlmDistPairingLedgerPeer::CREATED_ON);
        $sponsorDistPairingLedgerDB = MlmDistPairingLedgerPeer::doSelectOne($c);

        $legBalance = 0;
        if ($sponsorDistPairingLedgerDB) {
            $legBalance = $sponsorDistPairingLedgerDB->getBalance();
        }

        // update pairing balance
        $distPairingledger = new MlmDistPairingLedger();
        $distPairingledger->setDistId($distId);
        $distPairingledger->setLeftRight($position);
        $distPairingledger->setTransactionType($transactionType);
        $distPairingledger->setCredit(0);
        $distPairingledger->setDebit($debit);
        $distPairingledger->setBalance($legBalance - $debit);
        $distPairingledger->setRemark($remark);
        $distPairingledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $distPairingledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $distPairingledger->save();

        $this->revalidatePairing($distId, $position);
    }

    function flushDistPairingLeader($distId, $position, $minBalance, $remark)
    {
        $distPairingledger = new MlmDistPairingLedger();
        $distPairingledger->setDistId($distId);
        $distPairingledger->setLeftRight($position);
        $distPairingledger->setTransactionType(Globals::PAIRING_LEDGER_FLUSH);
        $distPairingledger->setCredit(0);
        $distPairingledger->setDebit($minBalance);
        $distPairingledger->setBalance(0);
        $distPairingledger->setRemark($remark);
        $distPairingledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $distPairingledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $distPairingledger->save();

        $this->revalidatePairing($distId, $position);
    }
}